随机划分数据集(matlab)

将训练数据按一定比例划分成训练数据和测试数据。

function [trainX,trainY,testX,testY] = split_train_test(X,Y,p)
% 训练数据的标签
c = unique(Y);
% 类别数
cn = length(c);
% 每类样本的数量
ecn = length(Y)/cn;

% 生成随机数
k = rand(1,ecn);
[m n] = sort(k);

trainX = [];
trainY = [];
testX = [];
testY = [];

a = ecn*p;
b = a+1;
for i = 1:cn
    num = n+ecn*(i-1);
    trainX = [trainX;X(num(1:a),:)];
    trainY = [trainY;Y(num(1:a),:)];
    testX = [testX;X(num(b:ecn),:)];
    testY = [testY;Y(num(b:ecn),:)];
end

你可能感兴趣的:(随机划分数据集(matlab))