keras加载MNIST数据集方法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/shaozhulei555/article/details/76144903

由于公司网络限制,因此使用keras自带的MNIST数据集加载方法

 

(x_train, y_train),(x_test, y_test) = mnist.load_data()

 

是不可行的,所以只能另辟蹊径。

 

第一种方法:

 

import gzip
import keras
from six.moves import cPickle
from keras import backend as K

img_rows, img_cols = 28, 28
def load_data():
    path =r'/root/keras/keras/datasets/mnist.pkl.gz'
    ifpath.endswith('.gz'):
        f =gzip.open(path, 'rb')
    else:
        f =gzip.open(path, 'rb')
    f =gzip.open(path, 'rb')
    data =cPickle.load(f)
    f.close()
    return data
print (len(load_data()))
 
(x_train, y_train), (x_validation, y_validation),(x_test, y_test) = load_data()
 
if K.image_data_format() == 'channels_first':
    x_train =x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test =x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape= (1, img_rows, img_cols)
else:
    x_train =x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test =x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape= (img_rows, img_cols, 1)
 
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

 

第二种

 

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
 
x_train, y_train = mnist.train.images,mnist.train.labels
x_test, y_test = mnist.test.images, mnist.test.labels
x_train = x_train.reshape(-1, 28, 28,1).astype('float32')
x_test = x_test.reshape(-1,28, 28,1).astype('float32')

备注:

目录 MNIST_data/ 下为四个文件t 10k-images.idx3-ubyte,t10k-labels.idx1-ubyte,train-images.idx3-ubyte,train-labels.idx1-ubyte

 

数据下载地址:

https://download.csdn.net/download/shaozhulei555/10829128 或

链接:https://pan.baidu.com/s/1gCHutXzpu6OaDbxbIs04Zw 密码:fhfa

 

 

 

展开阅读全文

没有更多推荐了,返回首页