1. 程式人生 > >keras載入MNIST資料集方法

keras載入MNIST資料集方法

由於公司網路限制,因此使用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