keras加载MNIST数据集方法

来源:互联网 发布:咫尺网络微页电话 编辑:程序博客网 时间:2024/06/05 15:53

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

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

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

 

第一种方法:

import gzipimport kerasfrom six.moves import cPicklefrom keras import backend as Kimg_rows, img_cols = 28, 28def 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 dataprint (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 /= 255x_test /= 255y_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_datamnist = input_data.read_data_sets("MNIST_data/", one_hot=True) x_train, y_train = mnist.train.images,mnist.train.labelsx_test, y_test = mnist.test.images, mnist.train.labelsx_train = x_train.reshape(-1, 28, 28,1).astype('float32')x_test = x_test.reshape(-1,28, 28,1).astype('float32')


原创粉丝点击