1. MNIST数据集:
机器学习的问题也就是**学习(训练)和推理(预测)**的处理
对于神经网络,首先使用训练数据进行权重的参数学习,再利用学习到的参数,对输入数据进行分类
2.MNIST数据下载和读入
load_mnist.py
# coding: utf-8
try:
import urllib.request
except ImportError:
raise ImportError('You should use Python 3.x')
import os.path
import gzip
import pickle
import os
import numpy as np
url_base = 'http://yann.lecun.com/exdb/mnist/'
key_file = {
'train_img':'train-images-idx3-ubyte.gz',
'train_label':'train-labels-idx1-ubyte.gz',
'test_img':'t10k-images-idx3-ubyte.gz',
'test_label':'t10k-labels-idx1-ubyte.gz'
}
dataset_dir = os.path.dirname(os.path.abspath(__file__))
save_file = dataset_dir + "/mnist.pkl"
train_num = 60000
test_num = 10000
img_dim = (1, 28, 28)
img_size = 784
def _download(file_name):
file_path = dataset_dir + "/" + file_name
if os.path.exists(file_path):
return
print("Downloading " + file_name + " ... ")
urllib.request.urlretrieve(url_base + file_name, file_path)
print("Done")
def download_mnist():
for v in key_file.values():
_download(v)
def _load_label(file_name):
file_path = dataset_dir + "/" + file_name
print("Converting " + file_name + " to NumPy Array ...")
with gzip.open(file_path, 'rb') as f:
labels = np.frombuffer(f.read(), np.uint8, offset=8)
print("Done")
return labels
def _load_img(file_name):
file_path = dataset_dir + "/" + file_name
print("Converting " + file_name + " to NumPy Array ...")
with gzip.open(file_path, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=16)
data = data.reshape(-1, img_size)
print("Done")
return data
def _convert_numpy():
dataset = {}
dataset['train_img'] = _load_img(key_file['train_img'])
dataset['train_label'] = _load_label(key_file['train_label'])
dataset['test_img'] = _load_img(key_file['test_img'])
dataset['test_label'] = _load_label(key_file['test_label'])
return dataset
def init_mnist():
download_mnist()
dataset = _convert_numpy()
print("Creating pickle file ...")
with open(save_file, 'wb') as f:
pickle.dump(dataset, f, -1)
print("Done!")
def _change_one_hot_label(X):
T = np.zeros((X.size, 10))
for idx, row in enumerate(T):
row[X[idx]] = 1
return T
def load_mnist(normalize=True, flatten=True, one_hot_label=False):
"""读入MNIST数据集
Parameters
----------
normalize : 将图像的像素值正规化为0.0~1.0
one_hot_label :
one_hot_label为True的情况下,标签作为one-hot数组返回
one-hot数组是指[0,0,1,0,0,0,0,0,0,0]这样的数组
flatten : 是否将图像展开为一维数组
Returns
-------
(训练图像, 训练标签), (测试图像, 测试标签)
"""
if not os.path.exists(save_file):
init_mnist()
with open(save_file, 'rb') as f:
dataset = pickle.load(f)
if normalize:
for key in ('train_img', 'test_img'):
dataset[key] = dataset[key].astype(np.float32)
dataset[key] /= 255.0
if one_hot_label:
dataset['train_label'] = _change_one_hot_label(dataset['train_label'])
dataset['test_label'] = _change_one_hot_label(dataset['test_label'])
if not flatten:
for key in ('train_img', 'test_img'):
dataset[key] = dataset[key].reshape(-1, 1, 28, 28)
return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label'])
if __name__ == '__main__':
init_mnist()
mnist_read.py
import sys, os
sys.path.append(os.pardir) # 为了导入父目录中的文件而进行的设定。因为minist.py在dataset文件夹中,python无法跨目录进行直接
# 导入,故需要这个语句进行设定
# sys.path.append(os.pardir)语句实际上是把父目录《python深度学习入》门加入到sys.path(python的搜索模块的路径集中),从而
# 可以导入《python深度学习入》下的任何目录(包括dataset目录)中的任何文件
from dataset.mnist import load_mnist
# 第一次会花费几分钟,因为要下载minist数据集,需要接入网络。第二次及以后的调用,只需要读入保存本地的文件(pickle文件即可)
(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)
# 输出各种形状
print(x_train.shape) # (60000, 784)
print(t_train.shape) # (60000,)
print(x_train.shape) # (10000,784)
print(t_test.shape) # (10000,)
3. ys.path.append(os.pardir)* :**
4. load_mnist函数以“(训练图像, 训练标签), (测试图像, 测试标签)”形式返回读入的MNIST数据
5. load_mnist(normalize=True, flatten=True, one-hot-label=False)
6. python中包含有pickle功能,可以将程序的运行中的对象保存为pkl文件形式,如果加载保存过的pickle文件,则可以立刻复原运行中的对像。第一次下载了mnist数据,则会保存为pickle文件,下一次读入mnist数据时,则方便很多。