文章目录
前言
在机器学习中训练模型时,经常需要按比例对数据集随机划分成训练集和测试集,本文总结了基于matlab和python的划分训练集和测试集的常用方法,仅供大家参考。
一、无序索引方法
1. matlab代码
% 确定随机种子,便于结果复现
rand('seed', 42);
% 生成和样本个数等长的无序索引序列
idx = randperm(length); % length即为样本的总数,idx为生成的无序索引
% 选取80%作为训练集
train_data = data(idx(1:0.8*length), :); % data为样本特征,格式为:样本数*特征数
train_labels = labels(idx(1:0.8*length), 1); % labels为样本标签,的格式为:样本数*1
% 剩余20%作为测试集
test_data = data( idx(0.8*length+1:end), :);
test_labels = labels( idx(0.8*length+1:end), 1);
2. python代码
length = data.shape[1]
# length = len(labels)
# 生成和样本个数等长的无序索引序列
index = randperm(length) # length即为样本的总数,idx为生成的无序索引
# 选取80%作为训练集(假设样本共100个)
idx1 = index[:80]
train_data = data[idx1] # data为样本特征,格式为:样本数*特征数
train_labels = labels[idx1] # labels为样本标签,的格式为:样本数*1
# 剩余20%作为测试集
idx2 = index[80:]
test_data = data[idx2]
test_labels = labels[idx2]
二、函数实现方法
1. 利用python库中的cross_validation.train_test_split方法
from numpy import random
import numpy as np
from sklearn import cross_validation
# 其中data为数据的特征矩阵,labels为标签,test_siz为测试的比例
x_train, x_test, y_train, y_test = cross_validation.train_test_split(data, labels, test_size=0.2, random_state=0)
2. 利用python库中的KFold方法(K折交叉验证方法)
from sklearn.model_selection import KFold
from sklearn import svm
# 其中data为数据的特征矩阵,labels为标签,train_index, test_index分别为训练集和测试集的样本索引
kf = KFold(n_splits=5)
for train_index, test_index in kf.split(data):
x_train, x_test = data[train_index], data[test_index]
y_train, y_test = labels[train_index], labels[test_index]
clf = svm.SVC(C=0.2, kernel='linear', decision_function_shape='ovo')
clf.fit(x_train, y_train)
pred_acc = clf.score(x_test, y_test)