MATLAB:使用for循环将分组向量中的患者划分为训练集与测试集
实现训练集与测试集的划分(基于for循环)
Got it, let's walk through how to split your Icross vector into Itest and Itrain using a for loop, just like you need.
首先明确你的数据结构:250个患者平均分成10组,每组25人。组1-5对应前125个样本,组6-10对应后125个样本。虽然直接索引切片会更简洁,但既然要求用for循环,我们可以按组遍历的方式来实现:
代码示例(以Python为例)
import numpy as np # 假设Icross是一个250×1的numpy向量(如果是列表,调整索引逻辑即可) Icross = np.random.rand(250, 1) # 用随机数模拟你的真实数据 # 初始化测试集和训练集容器 Itest = np.empty((0, 1)) Itrain = np.empty((0, 1)) group_size = 25 # 每组固定25人 # 遍历组1-5(索引0到4,对应第1至第5组),填充测试集 for group_idx in range(5): start_idx = group_idx * group_size end_idx = start_idx + group_size Itest = np.vstack((Itest, Icross[start_idx:end_idx, :])) # 遍历组6-10(索引5到9,对应第6至第10组),填充训练集 for group_idx in range(5, 10): start_idx = group_idx * group_size end_idx = start_idx + group_size Itrain = np.vstack((Itrain, Icross[start_idx:end_idx, :])) # 验证结果规模(应该都是125×1) print(f"测试集形状: {Itest.shape}") print(f"训练集形状: {Itrain.shape}")
代码逻辑解释
- 先定义每组人数
group_size=25,这样后续如果组数或每组人数调整,代码只需要改这一个参数。 - 第一个for循环处理前5组:通过组索引计算每组的起始/结束位置,把
Icross中对应片段拼接到Itest中。 - 第二个for循环处理后5组,逻辑和测试集完全一致,最终得到训练集
Itrain。
额外小提示
如果不需要严格用for循环(比如后续没有额外的组内处理逻辑),直接用切片会更高效简洁:
Itest = Icross[:125, :] # 直接取前125个样本(组1-5) Itrain = Icross[125:, :] # 直接取后125个样本(组6-10)
这种写法更适合常规的数据集划分场景,但如果你的需求必须依赖for循环(比如要在循环中加入组内数据预处理),前面的循环写法就完全符合要求啦。
内容的提问来源于stack exchange,提问作者florence-y
相关产品推荐
相关产品推荐

