【归纳总结】随机划分训练集和测试集

前言

在机器学习中训练模型时,经常需要按比例对数据集随机划分成训练集和测试集,本文总结了基于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)
  • 6
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坊间小木匠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值