kerasの基本的な使い方(3)--ニューラルネットワークを作成する

1896 ワード

作者:Tyan博客:noahsnail.com  |  CSDN  | 
本文は主にKerasのいくつかの基本的な使い方を紹介します.
  • Demo
  • from keras.datasets import mnist
    from keras.utils import np_utils
    from keras.models import Sequential
    from keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Flatten
    from keras.optimizers import Adam
    
    #  
    (X_train, y_train), (X_test, y_test) = mnist.load_data()
    
    #  
    X_train = X_train.reshape(-1, 1, 28, 28)
    X_test = X_test.reshape(-1, 1, 28, 28)
    
    #  label 
    y_train = np_utils.to_categorical(y_train, 10)
    y_test = np_utils.to_categorical(y_test, 10)
    
    
    #  
    model = Sequential()
    
    #  
    model.add(Conv2D(32, kernel_size = (5, 5), strides = (1, 1), padding = 'same', activation = 'relu', input_shape = (1, 28, 28)))
    
    #  
    model.add(MaxPooling2D(pool_size = (2, 2), strides = (1, 1), padding = 'same'))
    
    #  
    model.add(Conv2D(64, kernel_size = (5, 5), strides = (1, 1), padding = 'same', activation = 'relu'))
    
    #  
    model.add(MaxPooling2D(pool_size = (2, 2), strides = (1, 1), padding = 'same'))
    
    #  
    model.add(Flatten())
    model.add(Dense(1024))
    model.add(Activation('relu'))
    
    #  
    model.add(Dense(10))
    model.add(Activation('softmax'))
    
    #  
    adam = Adam(lr = 1e-4)
    
    #  、 、 
    model.compile(optimizer = adam, loss = 'categorical_crossentropy', metrics = ['accuracy'])
    
    #  
    model.fit(X_train, y_train, epochs = 2, batch_size = 32)
    
    #  
    loss, accuracy = model.evaluate(X_test, y_test)
    
    print ''
    print 'loss: ', loss
    print 'accuracy: ', accuracy
    
  • 結果
  • Using TensorFlow backend.
    Epoch 1/2
    60000/60000 [==============================] - 55s - loss: 0.4141 - acc: 0.9234
    Epoch 2/2
    60000/60000 [==============================] - 56s - loss: 0.0743 - acc: 0.9770
     9920/10000 [============================>.] - ETA: 0s
    loss:  0.103529265788
    accuracy:  0.9711