如何将notMNIST转成MNIST格式
相信了解机器学习的对MNIST不会陌生,Google的工程师Yaroslav Bulatov 创建了notMNIST,它和MNIST类似,图像28x28,也有10个Label(A-J)。
在Tensorflow中已经封装好了读取MNIST数据集的函数 read_data_sets(),
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
mnist = read_data_sets("data", one_hot=True, reshape=False, validation_size=0)
但是由于notMNIST的格式和MNIST的格式不是完全相同,所以基于tensorflow创建的针对MNIST的模型并不能直接读取notMNIST的图片。
Github上有人编写了格式转换代码(https://github.com/davidflanagan/notMNIST-to-MNIST),转换后可直接使用read_data_sets()完成读取,这样模型代码的变动就不会很大。本文是对在阅览完代码后所做的注释。
import numpy, imageio, glob, sys, os, random
#Imageio 提供简单的用于读写图像数据的接口
#glob 功能类似于文件搜索,查找文件只用到三个匹配符:”*”, “?”, “[]”。”*”匹配0个或多个字符;”?”匹配单个字符;”[]”匹配指定范围内的字符,如:[0-9]匹配数字。
def get_labels_and_files(folder, number):
# Make a list of lists of files for each label
filelists = []
for label in range(0,10):
filelist = []
filelists.append(filelist);
dirname = os.path.join(folder, chr(ord('A') + label))
#label实际为0-9,chr(ord('A') + label)返回A-J
#拼接路径dirname=folder/[A-J]
for file in os.listdir(dirname):
#返回一个装满当前路径中文件名的list
if (file.endswith('.png')):
fullname = os.path.join(dirname, file)
if (os.path.getsize(fullname) > 0):
filelist.append(fullname)
else:
print('file ' + fullname + ' is empty')
# sort each list of files so they start off in the same order
# regardless of how the order the OS returns them in
filelist.sort() # Take the specified number of items for each label and
# build them into an array of (label, filename) pairs
# Since we seeded the RNG, we should get the same sample each run
labelsAndFiles = []
for label in range(0,10):
filelist = random.sample(filelists[label], number)
#随机采样 设定个数的文件名
for filename in filelist:
labelsAndFiles.append((label, filename))
#Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。
return labelsAndFiles def make_arrays(labelsAndFiles):
images = []
labels = []
for i in range(0, len(labelsAndFiles)): # display progress, since this can take a while
if (i % 100 == 0):
sys.stdout.write("\r%d%% complete" % ((i * 100)/len(labelsAndFiles)))
#\r 返回第一个指针,覆盖前面的内容
sys.stdout.flush() filename = labelsAndFiles[i][1]
try:
image = imageio.imread(filename)
images.append(image)
labels.append(labelsAndFiles[i][0])
except:
# If this happens we won't have the requested number
print("\nCan't read image file " + filename) count = len(images)
imagedata = numpy.zeros((count,28,28), dtype=numpy.uint8)
labeldata = numpy.zeros(count, dtype=numpy.uint8)
for i in range(0, len(labelsAndFiles)):
imagedata[i] = images[i]
labeldata[i] = labels[i]
print("\n")
return imagedata, labeldata def write_labeldata(labeldata, outputfile):
header = numpy.array([0x0801, len(labeldata)], dtype='>i4')
with open(outputfile, "wb") as f:
#以二进制写模式打开
#这里使用了 with 语句,不管在处理文件过程中是否发生异常,都能保证 with 语句执行完毕后已经关闭了打开的文件句柄
f.write(header.tobytes())
#写入二进制数
f.write(labeldata.tobytes()) def write_imagedata(imagedata, outputfile):
header = numpy.array([0x0803, len(imagedata), 28, 28], dtype='>i4')
with open(outputfile, "wb") as f:
f.write(header.tobytes())
f.write(imagedata.tobytes()) def main(argv):
# Uncomment the line below if you want to seed the random
# number generator in the same way I did to produce the
# specific data files in this repo.
# random.seed(int("notMNIST", 36))
#当我们设置相同的seed,每次生成的随机数相同。如果不设置seed,则每次会生成不同的随机数 labelsAndFiles = get_labels_and_files(argv[1], int(argv[2]))
#随机排序
random.shuffle(labelsAndFiles) imagedata, labeldata = make_arrays(labelsAndFiles)
write_labeldata(labeldata, argv[3])
write_imagedata(imagedata, argv[4]) if __name__=='__main__':
#Make a script both importable and executable
#如果我们是直接执行某个.py文件的时候,该文件中那么”__name__ == '__main__'“是True
#如果被别的模块import,__name__!='__main__',这样main()就不会执行 main(sys.argv)
使用方法
下载解压notMNIST:
curl -o notMNIST_small.tar.gz http://yaroslavvb.com/upload/notMNIST/notMNIST_small.tar.gz
curl -o notMNIST_large.tar.gz http://yaroslavvb.com/upload/notMNIST/notMNIST_large.tar.gz
tar xzf notMNIST_small.tar.gz
tar xzf notMNIST_large.tar.gz
运行转换代码:
python convert_to_mnist_format.py notMNIST_small data/t10k-labels-idx1-ubyte data/t10k-images-idx3-ubyte
python convert_to_mnist_format.py notMNIST_large data/train-labels-idx1-ubyte data/train-images-idx3-ubyte
gzip data/*ubyte
如何将notMNIST转成MNIST格式的更多相关文章
- tensorflow学习笔记(10) mnist格式数据转换为TFrecords
本程序 (1)mnist的图片转换成TFrecords格式 (2) 读取TFrecords格式 # coding:utf-8 # 将MNIST输入数据转化为TFRecord的格式 # http://b ...
- CAFFE学习笔记(四)将自己的jpg数据转成lmdb格式
1 引言 1-1 以example_mnist为例,如何加载属于自己的测试集? 首先抛出一个问题:在example_mnist这个例子中,测试集是人家给好了的.那么如果我们想自己试着手写几个数字然后验 ...
- TensorFlow笔记五:将cifar10数据文件复原成图片格式
cifar10数据集(http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz)源格式是数据文件,因为训练需要转换成图片格式 转换代码: 注意文件路 ...
- asp.net dataTable转换成Json格式
/// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"> ...
- [jquery]将当前时间转换成yyyymmdd格式
如题: function nowtime(){//将当前时间转换成yyyymmdd格式 var mydate = new Date(); var str = "" + mydate ...
- MySQL Binlog Mixed模式记录成Row格式
背景: 一个简单的主从结构,主的binlog format是Mixed模式,在执行一条简单的导入语句时,通过mysqlbinlog导出发现记录的Binlog全部变成了Row的格式(明明设置的是Mixe ...
- [转] 将DOS格式文本文件转换成UNIX格式
点击此处阅读原文 用途说明 dos2unix命令用来将DOS格式的文本文件转换成UNIX格式的(DOS/MAC to UNIX text file format converter).DOS下的文本文 ...
- .NET调用外部接口将得到的List数据,并使用XmlSerializer序列化List对象成XML格式
BidOpeningData.BidSupervisionSoapClient client = new BidOpeningData.BidSupervisionSoapClient(); Dict ...
- 将序列化成json格式的日期(毫秒数)转成日期格式
<script> $(function () { loadInfo(); }) function loadInfo() { $.post("InfoList.ashx" ...
随机推荐
- tab切换插件开发
我开发的tab切换插件,基于jquery库,实现tab标签页的切换.插件的名称为jquery.tabSwitch.js. 插件实现代码如下: ; (function ($) { $.fn.tabSwi ...
- Redis 小白指南(三)- 事务、过期、消息通知、管道和优化内存空间
Redis 小白指南(三)- 事务.过期.消息通知.管道和优化内存空间 简介 <Redis 小白指南(一)- 简介.安装.GUI 和 C# 驱动介绍> 讲的是 Redis 的介绍,以及如何 ...
- 【2017-06-06】Ajax完整结构、三级联动的制作
一.Ajax完整结构 $.ajax({ url:"Main.ashx", data:{}, dataType:"json", type:"post&q ...
- servlet与jsp
Servlet生命周期 一.初始化阶段 当WEB客户第一次请求访问某个Servlet的时候,WEB容器将创建这个Servlet的实例.调用init()方法进行Servlet的初始化 一.响应客户请 ...
- 关于JQuery获取宽度和高度在chrome和IE下的不同
之前写了一个关于滚动条的东西,可是在写的时候发现JQuery在获取宽度和高度时在不同浏览器中是不一样的,下面发一下代码给给位看官先展示一下: $(function(){ $("#main&q ...
- charles连接手机抓包
写给我自己: 如果是使用charles抓包.一定要tm的保证手机和电脑连的是一个网. 1.proxy setting,查看charles,端口 2.勾选 3.ipconfig,查看自己电脑的ip地址 ...
- java环境变量最佳配置
1.打开我的电脑--属性--高级--环境变量 2.新建系统变量JAVA_HOME 和CLASSPATH 变量名:JAVA_HOME 变量值:C:\Program Files\Java\jdk1.7. ...
- JavaMail API
JavaMail API的核心类:会话.消息.地址.验证程序.传输,存储和文件夹.所有这些类都可以在JavaMail API即javax.mail的顶层包中找到,尽管你将频繁地发现你自己使用的子类是在 ...
- SQLServer数据库操作
--创建数据库create database 在线考试系统on(name=在线考试系统_DATA,filename='E:\DB\在线考试系统_DATA.mdf',size=5mb,maxsize=2 ...
- MVC在VIEW中动态控制htmlAttributes的方法
@{ IDictionary<string, object> dic = new Dictionary<string, object>(); dic.Add("cla ...