kerasロードモデル

1710 ワード

説明:このプログラムは2つの非表示層を含むニューラルネットワークです.保存したモデルをロードする方法を示します.データセット:MNIST

1.kerasモジュールのロード

from __future__ import print_function
#Python __future__ , , 。
import numpy as np
np.random.seed(1337) # for reproducibility

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense,Dropout,Activation
from keras.optimizers import SGD,Adam,RMSprop
from keras.utils import np_utils
load_model
from keras.models import load_model
  • 変数初期化
  • batch_size = 128 
    nb_classes = 10
    nb_epoch = 20 
    
  • 準備データ
  • # the data, shuffled and split between train and test sets
    (X_train, y_train), (X_test, y_test) = mnist.load_data()
    
    X_train = X_train.reshape(60000, 784)
    X_test = X_test.reshape(10000, 784)
    X_train = X_train.astype('float32')
    X_test = X_test.astype('float32')
    X_train /= 255
    X_test /= 255
    print(X_train.shape[0], 'train samples')
    print(X_test.shape[0], 'test samples')
    
    # 
    # convert class vectors to binary class matrices
    Y_train = np_utils.to_categorical(y_train, nb_classes)
    Y_test = np_utils.to_categorical(y_test, nb_classes)
    
  • モデル
  • を構築
    # 
    model=load_model('mnist-mpl.h5')
    # 
    model.summary()
    
  • 訓練と評価
  • # 
    model.compile(loss='categorical_crossentropy',
                  optimizer=RMSprop(),
                  metrics=['accuracy'])
    
  • モデル評価
  • score = model.evaluate(X_test, Y_test, verbose=0)
    print('Test score:', score[0])
    print('Test accuracy:', score[1])