相信了解机器学习的对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格式的更多相关文章

  1. tensorflow学习笔记(10) mnist格式数据转换为TFrecords

    本程序 (1)mnist的图片转换成TFrecords格式 (2) 读取TFrecords格式 # coding:utf-8 # 将MNIST输入数据转化为TFRecord的格式 # http://b ...

  2. CAFFE学习笔记(四)将自己的jpg数据转成lmdb格式

    1 引言 1-1 以example_mnist为例,如何加载属于自己的测试集? 首先抛出一个问题:在example_mnist这个例子中,测试集是人家给好了的.那么如果我们想自己试着手写几个数字然后验 ...

  3. TensorFlow笔记五:将cifar10数据文件复原成图片格式

    cifar10数据集(http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz)源格式是数据文件,因为训练需要转换成图片格式 转换代码: 注意文件路 ...

  4. asp.net dataTable转换成Json格式

    /// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"> ...

  5. [jquery]将当前时间转换成yyyymmdd格式

    如题: function nowtime(){//将当前时间转换成yyyymmdd格式 var mydate = new Date(); var str = "" + mydate ...

  6. MySQL Binlog Mixed模式记录成Row格式

    背景: 一个简单的主从结构,主的binlog format是Mixed模式,在执行一条简单的导入语句时,通过mysqlbinlog导出发现记录的Binlog全部变成了Row的格式(明明设置的是Mixe ...

  7. [转] 将DOS格式文本文件转换成UNIX格式

    点击此处阅读原文 用途说明 dos2unix命令用来将DOS格式的文本文件转换成UNIX格式的(DOS/MAC to UNIX text file format converter).DOS下的文本文 ...

  8. .NET调用外部接口将得到的List数据,并使用XmlSerializer序列化List对象成XML格式

    BidOpeningData.BidSupervisionSoapClient client = new BidOpeningData.BidSupervisionSoapClient(); Dict ...

  9. 将序列化成json格式的日期(毫秒数)转成日期格式

    <script> $(function () { loadInfo(); }) function loadInfo() { $.post("InfoList.ashx" ...

随机推荐

  1. 线程机制、CLR线程池以及应用程序域

    最近在总结多线程.CLR线程池以及TPL编程实践,重读一遍CLR via C#,比刚上班的时候收获还是很大的.还得要多读书,读好书,同时要多总结,多实践,把技术研究透,使用好. 话不多说,直接上博文吧 ...

  2. phpcms通过URL传参

    在PHPCMS中都会遇到通过URL传参数的问题,但是默认的只能取到$catid.$page等这类的值,特别是伪静态之后,想获得其他参数根本不可能,有的人用$_GET["参数"]这种 ...

  3. std::forward_list

    forward_list相比list来说空间利用率更好,与list一样不支持随机访问,若要访问除头尾节点的其他节点则时间复杂度为线性. 在forward_list成员函数里只能访问头节点以及向头节点插 ...

  4. bootstrap 架构知识点

    .col-md-pull-2 向右相对定位偏移量 .col-md-push-2 向左相对定位偏移量 .pull-left 左浮动 .pull-right 右浮动     改变大小写 通过这几个类可以改 ...

  5. 搭建rtmp直播流服务之4:videojs和ckPlayer开源播放器二次开发(播放rtmp、hls直播流及普通视频)

    前面几章讲解了使用 nginx-rtmp搭建直播流媒体服务器; ffmpeg推流到nginx-rtmp服务器; java通过命令行调用ffmpeg实现推流服务; 从数据源获取,到使用ffmpeg推流, ...

  6. 修复python的ModuleNotFoundError

    我在项目里面用到了python,但其他的同事并没有安装python环境,为了不强制每个人都安装python,我下载了python-3.6.1-embed-amd64,并将用一个.bat去调用它. 大概 ...

  7. Django中通过filter和simple_tag为前端实现自定义函数

    Django的模板引擎提供了一般性的功能函数,通过前端可以实现多数的代码逻辑功能,这里称之为一般性,是因为它仅支持大多数常见情况下的函数功能,例如if判断,ifequal对比返回值等,但是稍微复杂一些 ...

  8. android蓝牙学习

    学习路线 1 蓝牙权限 <uses-permission android:name="android.permission.BLUETOOTH" /> <uses ...

  9. 逻辑关系下的NN应用

    ​ 自己好奇搜了几篇别人对Ng视频的的笔记,读下去可观性很强,后回到自己的笔记却觉得矛盾很多,有些地方搞得很模糊,自己没有仔细去想导致写完读起来很怪,此篇之后我决定放慢记笔记的速度,力求尽多地搞清楚模 ...

  10. 关于Handler的理解,子线程不能更新UI的纠正和回调的思考

    开发Android这么久了,总会听到有人说:主线程不能访问网络,子线程不能更新UI.Android的主线程的确不能长时间阻塞,但是子线程为什么不能更新UI呢?今天把这些东西整理,顺便在子线程更新UI. ...