Python数据集切分实例

yipeiwu_com7年前Python基础

在处理数据过程中经常要把数据集切分为训练集和测试集,因此记录一下切分代码。

'''
data:数据集
test_ratio:测试机占比
如果data为numpy.numpy.ndarray直接使用此代码
如果data为pandas.DatFrame类型则
  return data[train_indices],data[test_indices]
修改为
  return data.iloc[train_indices],data.iloc[test_indices]
'''
def split_train(data,test_ratio):
  shuffled_indices=np.random.permutation(len(data))
  test_set_size=int(len(data)*test_ratio)
  test_indices =shuffled_indices[:test_set_size]
  train_indices=shuffled_indices[test_set_size:]
  return data[train_indices],data[test_indices]

测试代码如下:

import numpy as np
import pandas as pd
data=np.random.randint(100,size=[25,4])
print(data)

结果如下:

Python数据集切分

Python数据集切分

从上图可以看出,原数据集按照5:1被随机分为两部分。但是此种方法存在一个缺点–每次调用次函数切分同一个数据集切分出来的结果都不一样,因此常在np.random.permutation(len(data))先调用np.random.seed(int)函数,来确保每次切分来的结果相同。

因此将上述函数改为:

def split_train(data,test_ratio):
  np.random.seed(43)
  shuffled_indices=np.random.permutation(len(data))
  test_set_size=int(len(data)*test_ratio)
  test_indices =shuffled_indices[:test_set_size]
  train_indices=shuffled_indices[test_set_size:]
  return data[train_indices],data[test_indices]

这个函数np.random.seed(43)当参数为同一整数时产生的随机数相同。

以上这篇Python数据集切分实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

numpy np.newaxis 的实用分享

如下所示: >> type(np.newaxis) NoneType >> np.newaxis == None True np.newaxis 在使用和功...

Python Selenium Cookie 绕过验证码实现登录示例代码

Python Selenium Cookie 绕过验证码实现登录示例代码

之前介绍过通过cookie 绕过验证码实现登录的方法。这里并不多余,会增加分析和另外一种方法实现登录。 1、思路介绍  1.1、直接看代码,内有详细注释说明 # File...

python sqlobject(mysql)中文乱码解决方法

UnicodeEncodeError: 'latin-1' codec can't encode characters in position; 找了一天终于搞明白了,默认情况下,mys...

利用pyinstaller打包exe文件的基本教程

前言 PyInstaller可以用来打包python应用程序,打包完的程序就可以在没有安装Python解释器的机器上运行了。PyInstaller支持Python 2.7和Python...

python3.x提取中文的正则表达式示例代码

实例一: 读取txt文件中含有中文的字符 import re ##此处使用的编辑器是python3.x d="[\u4e00-\u9fa5]+" #中文匹配的符号 f=open('...