随机切分深度学习训练集、验证集、测试集

**目的:**将1.6万条数据随机切分成训练集、开发集、测试集。
参考了python随机读取txt文档某一行的源码,源码如下:

#coding=utf-8
#! /usr/bin/python
import random
import linecache
def hello():
count = len(open('hello.txt','rU').readlines())#获取行数
hellonum=random.randrange(1,count, 1)#生成随机行数
return linecache.getline('hello.txt',hellonum)#随机读取某行
if __name__ == "__main__":

hello()

基于上述源码实现了随机切分实验数据。具体的划分比例可以在while循环里设置。源码如下:

import random
import linecache

m=0
with open(r'./data/sz_text_all.txt','rb') as f:
    data = f.read().decode('utf-8')      #python3一定要加上这句不然会编码报错!
    #获取txt的总行数!
    n = data.count('\n')
    print("总行数",n)
    #创建字典,将生成的随机数存入该字典
    num_dict = {}

    #选取随机的数
    while m <= n:
        i = random.randint(1, (n+1))
        if i in num_dict :continue
        num_dict[i] = i
        print("本次使用的行数",i)
        ###得到对应的i行的数据
        line=linecache.getline(r'./data/sz_text_all.txt',i)
        if m<=500:#切分500条开发集
            with open('./dev.txt','a' ,encoding='utf-8') as dev_f:
                dev_f.write(line)
                #print(line)
        elif m>500 and m<=1000:#500条测试集
            with open('./test.txt','a' ,encoding='utf-8') as test_f:
                test_f.write(line)
                #print(line)
        else :#随机切分1.5万条训练集
            with open('./train.txt','a' ,encoding='utf-8') as train_f:
                train_f.write(line)
                #print(line)

        m+=1

print("done!")

欢迎扫码关注博主公众号“自然语言处理与算法”,更多干货直达~
在这里插入图片描述

参考:
http://www.etwiki.cn/python/634.html
https://www.cnblogs.com/botoo/p/7356737.html

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值