keras加载MNIST数据集方法

时间:2021-09-27 13:53:49

由于公司网络限制,因此使用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.train.labels
x_train = x_train.reshape(-1, 28, 28,1).astype('float32')
x_test = x_test.reshape(-1,28, 28,1).astype('float32')