开源标准数据集 —— mnist(手写字符识别)

下载地址:mnist.pkl.gz

1. 使用 python 读取和解析 mnist.pkl.gz

import pickle
import gzip
from PIL import Image def load_data():
with gzip.open('./mnist.pkl.gz') as fp:
training_data, valid_data, test_data = pickle.load(fp)
return training_data, valid_data, test_data training_data, valid_data, test_data = load_data()
print len(training_data[0])
print len(valid_data[0])
print len(test_data[0])
print len(training_data[0][0]) I = training_data[0][0]
I.resize((28, 28))
im = Image.fromarray((I*256).astype('uint8'))
im.show()
im.save('5.png')

可以看出,mnist.pkl.gz 分为训练集,校验集和测试集;

使用 PIL 中的图像相关 api,我们可对其中的图像显示出来并保存;

2. Python中的单行、多行、中文注释

在大量的数据处理或者计算机视觉的文献和著作中,我们常见如下的数据集可视化(甚至对参数也可进行可视化,毕竟图像的本质是二维数组),通过文章末尾的代 码我们发现只需对布局及间距的慎重设置,便可对大量丰富的图像以”地板贴砖(tiles on a floor)”的形式进行组织,也即可视化,展示数据或相关工作,可以起到十分直观的效果,下图即是对深度神经网络的权值矩阵进行的贴砖可视化:

def normalize(darr, eps=1e-8):
# normalize(x) = (x-min)/(max-min)
darr -= darr.min()
darr *= 1./(darr.max()+eps)
return darr def tile_raster_images(X, image_shape, tile_shape,
tile_spacing=(0, 0), normalize_rows=True, output_pixel_vals=True):
# image_shape:每一个砖的高和宽,
# tile_shape:在横纵两个方向上分别有多少砖
# tile_spacing:砖与砖之间的距离
# normalize_rows:是否对砖进行归一化
# output_pixel_vals:是否对砖以图像的形式进行显示 assert len(image_shape) == 2
assert len(tile_shape) == 2
assert len(tile_spacing) == 2
# 对参数进行断言,确保它们都是二维元组
output_shape = [
(ishp + tsp)*tshp-tsp
for ishp, tshp, tsp in zip(image_shape, tile_shape, tile_spacing)
]
# image_shape == (28, 28) mnist data
# tile_shape == (10, 10), tile_spacing == (1, 1)
# [(28+1)*10-1]*[(28+1)*10-1] H, W = image_shape
Hs, Ws = tile_spacing
dt = 'uint8' if output_pixel_vals else X.dtype
# python 风格的三目运算符
output_array = numpy.zeros(output_shape, dtype=dt) # 开始贴砖
for i in range(tile_shape[0]):
for j in range(tile_shape[1]):
if i*tile_shape[1]+j < X.shape[0]:
# X的每一行是一个图像(二维)flatten后的(一维的行向量)
this_x = X[i*tile_shape[1]+j]
this_image = normalize(this_x.reshape(image_shape)) if normalize_rows else this_x.reshape(image_shape)
c = 255 if output_pixel_vals else 1
output_array[
i*(H+Hs):i*(H+Hs)+H, j*(W+Ws):j*(W+Ws)+W
] = this_image*c
return output_array import numpy
from PIL import Image X = numpy.random.randn(500, 28*28)
arr = tile_raster_images(X, image_shape=(28, 28),
tile_shape=(12, 12), tile_spacing=(1, 1))
img = Image.fromarray(arr)
img.show()
img.save('./砖块可视化.png')
# 这里也可使用 matplotlib 进行显示
# plt.imshow(img, cmap='gray')
# plt.show()

可视化可以更直观的观察数据,让工作更加高效。

3. 数据可视化,贴砖

一、python单行注释符号(#)

示例:#this is a comment

二、批量、多行注释符号

多行注释是用三引号”’ ”’包含的,引号可以使单引号也可以是双引号

例如:

'''
ABC
ABC
ABC
'''
"""
ABC
ABC
ABC
"""

三、python中文注释方法

如果文件里有非ASCII字符,需要在第一行或第二行指定编码声明。把ChineseTest.py文件的编码重新改为ANSI,并加上编码声明:

一定要在第一行或者第二行加上这么一句话:

#coding=utf-8

# -*- coding: utf-8 -*-

我刚开始加上了依然出错,是因为我的py文件的前三行是注释声明,我把这句话放在了第四行,所以依然报错。

py脚本的前两行一般都是:

#!/usr/bin/python

# -*- coding: utf-8 -*-

python 读写数据的更多相关文章

  1. python读写数据篇

    一.读写数据1.读数据 #使用open打开文件后一定要记得调用文件对象的close()方法.比如可以用try/finally语句来确保最后能关闭文件.file_object = open('thefi ...

  2. python操作txt文件中数据教程[1]-使用python读写txt文件

    python操作txt文件中数据教程[1]-使用python读写txt文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 原始txt文件 程序实现后结果 程序实现 filename = '. ...

  3. Python StringIO实现内存缓冲区中读写数据

    StringIO的行为与file对象非常像,但它不是磁盘上文件,而是一个内存里的“文件”,我们可以像操作磁盘文件那样来操作StringIO.这篇文章主要介绍了Python StringIO模块,此模块 ...

  4. Python 学习 第17篇:从SQL Server数据库读写数据

    在Python语言中,从SQL Server数据库读写数据,通常情况下,都是使用sqlalchemy 包和 pymssql 包的组合,这是因为大多数数据处理程序都需要用到DataFrame对象,它内置 ...

  5. Python中异常和JSON读写数据

    异常可以防止出现一些不友好的信息返回给用户,有助于提升程序的可用性,在java中通过try ... catch ... finally来处理异常,在Python中通过try ... except .. ...

  6. Python读写文件

    Python读写文件1.open使用open打开文件后一定要记得调用文件对象的close()方法.比如可以用try/finally语句来确保最后能关闭文件. file_object = open('t ...

  7. python 读写、创建 文件

    python中对文件.文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目 ...

  8. [转]用Python读写Excel文件

    [转]用Python读写Excel文件   转自:http://www.gocalf.com/blog/python-read-write-excel.html#xlrd-xlwt 虽然天天跟数据打交 ...

  9. [Python]读写文件方法

    http://www.cnblogs.com/lovebread/archive/2009/12/24/1631108.html [Python]读写文件方法 http://www.cnblogs.c ...

随机推荐

  1. POJ 3468.A Simple Problem with Integers-线段树(成段增减、区间查询求和)

    POJ 3468.A Simple Problem with Integers 这个题就是成段的增减以及区间查询求和操作. 代码: #include<iostream> #include& ...

  2. Educational Codeforces Round 33 (Rated for Div. 2) D. Credit Card

    D. Credit Card time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...

  3. Codeforces Round #447 (Div. 2) A. QAQ【三重暴力枚举】

    A. QAQ time limit per test 1 second memory limit per test 256 megabytes input standard input output ...

  4. nodejs微服务

    近来公司增加了nodejs微服务 它的主要任务是接收来自于现场的采集数据:作业记录和流转记录,动态构建一个基地的全景实时数据        暂时不涉及数据库. 如果要进行数据库操作,不建议使用本模块, ...

  5. poj2763(树链剖分 - 边权)

    poj2763 题意 给定一个树形图,某人原来在 s 点,每条边(路)有通过的时间花费,有两种操作:1. 查询某人到 u 点花费的时间 2. 更新某条路的时间花费. 分析 权值在边上,可以把它们 &q ...

  6. hdu 1506 Largest Rectangle in a Histogram 构造

    题目链接:HDU - 1506 A histogram is a polygon composed of a sequence of rectangles aligned at a common ba ...

  7. 程设刷题 | 程序设计实践II-2017(部分)

    目录 1165-算术题 题目描述 代码实现 1184-Tourist 1 题目描述 代码实现 1186-Tourist 2 题目描述 代码实现 1224-LOVE 题目描述 代码实现 1256-湘潭大 ...

  8. 使用Bundle在Activity间传递数据

    使用Bundle在Activity间传递数据 源Activity public class SourceActivty extends Activity { private Intent intent ...

  9. sql server 性能调优 资源等待之网络I/O

    原文:sql server 性能调优 资源等待之网络I/O 一.概述 与网络I/O相关的等待的主要是ASYNC_NETWORK_IO,是指当sql server返回数据结果集给客户端的时候,会先将结果 ...

  10. 发布Android开源库,看这个文章就够了!

    最近在Flipboard实习期间写了一个轮播工具,技术上没什么难点,不过动画效果还是不错的,决定改改代码写个库开源出去.项目地址:http://github.com/chengdazhi/Decent ...