深さ学習tenssorflow基礎mnist

6689 ワード

ソフトウェアアーキテクチャ
mnistデータセットの識別は、非常に小さいネットワークを2つ使用して実現されています。最初は最も簡単な全接続ネットワーク、2番目は畳み込みネットワーク、mnistデータセットは入門データセットですので、画像増強は不要です。またはジェネレータでメモリを読み込むことで、簡単なfit()コマンドを直接使用すれば、1回限りのトレーニングが可能です。
チュートリアルをインストール
  • で使用された主なサードパーティライブラリは、tensorFlow 1.x、TensorFlowベースのKerasがあり、ベースのライブラリはnumpy、matplotlib
  • が含まれています。
  • インストールも簡単です。例えば、pip install numpy-ihttps://pypi.tuna.tsinghua.edu.cn/simple
  • 注意テナントflowバージョンは2.x
  • ではありません。
    使用説明
  • まず、データセットをプレビューして、mnistplt.pyを実行して、4つのトレーニング用の画像を描きました。
  • 全接続ネットワークを訓練するとDensemist.pyが実行され、重みDense.h 5が得られ、モデルをロードし、Denseload.py
  • が実行されると予測される。
  • トレーニング畳み込みネットワークはCNNmnist.pyを実行し、重みCNN.h 5を得てモデルをロードし、CNNload.py
  • を実行すると予測される。
    結果図
    在这里插入图片描述
    在这里插入图片描述
    トレーニングプロセスのコメント
    全接続ネットワークトレーニング:
    
    """       """
    from tensorflow.examples.tutorials.mnist import input_data
    from keras.models import  Sequential
    from keras.layers import Dense
    #          
    img_size=28
    num=10
    mnist=input_data.read_data_sets("./data",one_hot=True)
    X_train,y_train,X_test,y_test=mnist.train.images,mnist.train.labels,mnist.test.images,mnist.test.labels
    X_train=X_train.reshape(-1,img_size,img_size)
    X_test=X_test.reshape(-1,img_size,img_size)
    X_train=X_train*255
    X_test=X_test*255
    y_train=y_train.reshape(-1,num)
    y_test=y_test.reshape(-1,num)
    print(X_train.shape)
    print(y_train.shape)
    #          
    num_pixels = X_train.shape[1] * X_train.shape[2]
    X_train = X_train.reshape(X_train.shape[0],num_pixels).astype('float32')
    X_test = X_test.reshape(X_test.shape[0],num_pixels).astype('float32')
    #   
    X_train=X_train/255
    X_test=X_test/255
    # one hot  ,     ,  
    #y_train = np_utils.to_categorical(y_train)
    #y_test = np_utils.to_categorical(y_test)
    #    
    def baseline():
        """
        optimizer:   , Adam
        loss:    ,   categorical_crossentropy     ,        ,      10   ,
                     10    ,              1   0
        metrics:   ,                   
        """
        model=Sequential()
        #            :       input_dim    ,  , 784      ,   num_pixels。
        #     Dense   :             ,             ,      0 0.05        (uniform
        #Keras         ,             normal,                     
        model.add(Dense(num_pixels,input_dim=num_pixels,kernel_initializer='normal',activation='relu'))
        #softmax                 
        model.add(Dense(num,kernel_initializer='normal',activation='softmax'))
        #categorical_crossentropy        ,   softmax             
        model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
        return model
    #    
    model = baseline()
    """
    batch_size
      
              。
       ,   32
    epochs
      
            
    verbose
        ,  
    0:              
    1:     
    2:  epoch      
          2000          ,  2000          500   batch,       epoch    4   iteration
    """
    model.fit(X_train,y_train,validation_data=(X_test,y_test),epochs=10,batch_size=200,verbose=2)
    #      
    model.summary()
    #model.evaluate()                (  ,  accuracy)
    """
    verbose:         
    verbose = 0               
    verbose = 1         
    """
    scores = model.evaluate(X_test,y_test,verbose=0)
    print(scores)
    #    
    model_dir="./Dense.h5"
    model.save(model_dir)
    CNNトレーニング:
    
    """
           
    Sequential     :  (layers)     ,           ,      ,         
                   ,    (   )   
    3  RGB  ,      3        ,     1    
    """
    import numpy as np
    from tensorflow.examples.tutorials.mnist import input_data
    from keras.models import Sequential
    from keras.layers import Dense
    from keras.layers import Dropout
    #Flatten      “  ”,          ,
    #               
    from keras.layers import Flatten
    from keras.layers.convolutional import Conv2D
    from keras.layers.convolutional import MaxPooling2D
    #          
    img_size=28
    num=10
    mnist=input_data.read_data_sets("./data",one_hot=True)
    X_train,y_train,X_test,y_test=mnist.train.images,mnist.train.labels,mnist.test.images,mnist.test.labels
    X_train=X_train.reshape(-1,img_size,img_size)
    X_test=X_test.reshape(-1,img_size,img_size)
    X_train=X_train*255
    X_test=X_test*255
    y_train=y_train.reshape(-1,num)
    y_test=y_test.reshape(-1,num)
    print(X_train.shape) #(55000, 28, 28)
    print(y_train.shape) #(55000, 10)
    #               input_shape  
    X_train = X_train.reshape(X_train.shape[0],28,28,1).astype('float32')
    X_test = X_test.reshape(X_test.shape[0],28,28,1).astype('float32')
    print(X_train.shape)#(55000,28,28,1)
    #   
    X_train=X_train/255
    X_test=X_test/255
    # one hot  ,     ,  
    #y_train = np_utils.to_categorical(y_train)
    #y_test = np_utils.to_categorical(y_test)
    #  CNN  
    def CNN():
        """
               。   32 feature map,        ,  [pixels][width][height]       。feature map    1*5*5,      ‘relu'    
            pooling ,   MaxPooling,   2*2
        Flatten               
                , 128    ,      ‘relu'
                , 10    ,           ,                 
        """
        model = Sequential()
        model.add(Conv2D(32, (5, 5), input_shape=(img_size,img_size,1), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))
        model.add(Flatten())
        model.add(Dense(128, activation='relu'))
        model.add(Dense(num, activation='softmax'))
        #  
        model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
        return model
    #    
    model=CNN()
    model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=5, batch_size=200, verbose=1)
    model.summary()
    scores = model.evaluate(X_test,y_test,verbose=1)
    print(scores)
    #    
    model_dir="./CNN.h5"
    model.save(model_dir)
    ここでmnistに関する記事を紹介します。これからもよろしくお願いします。もっと深い学習内容について、私達の以前の文章を検索してください。または次の関連記事を引き続き閲覧してください。これからもよろしくお願いします。