在线下载MNIST数据集(深度学习⼊门基于Python的理论与实
现——源代码)
mnist.py (功能,在线下载MNIST数据集)
# coding: utf-8
try:
quest
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 = 'yann.lecun/exdb/mnist/'
key_file = {
'train_img':'',
'train_label':'',
'test_img':'',
'test_label':''
}
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 ists(file_path):
return
print("Downloading " + file_name + " ... ")
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.ad(), 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:
with gzip.open(file_path, 'rb') as f:
data = np.ad(), np.uint8, offset=16)
data = shape(-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 ists(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_show.py(⽤于读取图像信息,并显⽰,需要将mnist.py和mnist_show.py存放在同⼀⽬录下(可以不同级),先运⾏mnist.py在线下载数据集,再使⽤mnist_show.py读取并显⽰其中某⼀幅图)
# coding: utf-8
import sys, os
sys.path.append(os.pardir) # 为了导⼊⽗⽬录的⽂件⽽进⾏的设定
import numpy as np
ist import load_mnist
from PIL import Image
def img_show(img):
pil_img = Image.fromarray(np.uint8(img))
pil_img.show()
(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)
img = x_train[0] #改变序号可以读取不同的图⽚
label = t_train[0] #改变序号可以读取不同的图⽚
print(label) # 5
print(img.shape) # (784,)
img = shape(28, 28) # 把图像的形状变为原来的尺⼨
print(img.shape) # (28, 28)
img_show(img)
常见问题:
1. 运⾏mnist_show.py时可能会出现以下错误:ModuleNotFoundError: No module named 'PIL'或者NameError: name 'Image' is not defined.
解决办法:
1. 这其实是电脑上没有装Pillow或者pillow版本较低,可以使⽤“pip install Pillow”安装pillow,并根据提⽰使⽤“python -m pip install --upgrade pip”将pillow升级⾄最⾼版本(version18.1).
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论