如何在Matlab/Octave中按8:2比例拆分数据集为训练集和测试集?
Split Dataset into 80% Train / 20% Test in MATLAB/Octave
Hey there! Let's walk through how to create the logical indices idxTrain and idxTest you need—where training samples are marked as 1 and test samples as 0. This approach works seamlessly in both MATLAB and Octave.
Implementation Code
First, assuming you already have N = length(data.x) defined, here's the full, clean snippet:
% Calculate number of training samples (80% of total dataset) numTrain = round(N * 0.8); % Generate a random permutation of indices to avoid bias from original data order permutedIdx = randperm(N); % Initialize logical arrays with all false values idxTrain = false(1, N); idxTest = false(1, N); % Mark the first 80% of permuted indices as training samples idxTrain(permutedIdx(1:numTrain)) = true; % Test set is the direct complement of the training set idxTest = ~idxTrain;
Key Details & Practical Tips
- Randomness & Reproducibility: Using
randpermensures your split is random each run. If you need consistent splits for debugging or comparison, set a random seed first withrng(42);(replace 42 with any integer of your choice). - Handling Non-Divisible Sample Counts: If
Nisn't a multiple of 5,round(N * 0.8)adjusts to the nearest integer. For strictly ≤80% training samples, usefloor(N * 0.8); for strictly ≥80%, useceil(N * 0.8). - Octave Compatibility: Every line here works in Octave without any syntax changes—
randpermand logical operations behave identically across both platforms.
内容的提问来源于stack exchange,提问作者hello
相关产品推荐
相关产品推荐

