Beispiel #1
0
def main():
    """
    TensorFlow を用いた RNN Encoder-Decoder(LSTM 使用) による簡単な質問応答(足し算)処理
    """
    print("Enter main()")

    # Reset graph
    #ops.reset_default_graph()

    #======================================================================
    # データセットを読み込み or 生成
    # Import or generate data.
    #======================================================================
    X_features, y_labels, dict_str_to_idx, dict_idx_to_str = MLPreProcess.generate_add_uint_operation_dataset( n_samples = 20000, digits = 3, seed = 12 )
    print( "X_features.shape :", X_features.shape )
    print( "y_labels :", y_labels.shape )
    print( "dict_str_to_idx :", dict_str_to_idx )
    print( "dict_idx_to_str :", dict_idx_to_str )

    #======================================================================
    # データを変換、正規化
    # Transform and normalize data.
    # ex) data = tf.nn.batch_norm_with_global_normalization(...)
    #======================================================================

    
    #======================================================================
    # データセットをトレーニングデータ、テストデータ、検証データセットに分割
    #======================================================================
    X_train, X_test, y_train, y_test \
    = MLPreProcess.dataTrainTestSplit( X_input = X_features, y_input = y_labels, ratio_test = 0.1, input_random_state = 1 )

    #======================================================================
    # アルゴリズム(モデル)のパラメータを設定
    # Set algorithm parameters.
    # ex) learning_rate = 0.01  iterations = 1000
    #======================================================================
    learning_rate1 = 0.001
    adam_beta1 = 0.9        # For the Adam optimizer
    adam_beta2 = 0.999      # For the Adam optimizer

    rnn1 = RecurrectNNEncoderDecoderLSTM(
               session = tf.Session(),
               n_inputLayer = 12,                   # 12 : "0123456789+ " の 12 文字
               n_hiddenLayer = 128,                 # rnn の cell 数と同じ
               n_outputLayer = 12,                  # 12 : "0123456789+ " の 12 文字
               n_in_sequence_encoder = 7,           # エンコーダー側のシーケンス長 / 足し算の式のシーケンス長 : "123 " "+" "456 " の計 4+1+4=7 文字
               n_in_sequence_decoder = 4,           # デコーダー側のシーケンス長 / 足し算の式の結果のシーケンス長 : "1000" 計 4 文字
               epochs = 20000,
               batch_size = 100,
               eval_step = 1
           )
    rnn1.print( "after __init__()" )

    #======================================================================
    # 変数とプレースホルダを設定
    # Initialize variables and placeholders.
    # TensorFlow は, 損失関数を最小化するための最適化において,
    # 変数と重みベクトルを変更 or 調整する。
    # この変更や調整を実現するためには, 
    # "プレースホルダ [placeholder]" を通じてデータを供給(フィード)する必要がある。
    # そして, これらの変数とプレースホルダと型について初期化する必要がある。
    # ex) a_tsr = tf.constant(42)
    #     x_input_holder = tf.placeholder(tf.float32, [None, input_size])
    #     y_input_holder = tf.placeholder(tf.fload32, [None, num_classes])
    #======================================================================
    

    #======================================================================
    # モデルの構造を定義する。
    # Define the model structure.
    # ex) add_op = tf.add(tf.mul(x_input_holder, weight_matrix), b_matrix)
    #======================================================================
    rnn1.model()
    rnn1.print( "after model()" )

    #======================================================================
    # 損失関数を設定する。
    # Declare the loss functions.
    #======================================================================
    rnn1.loss( CrossEntropy() )

    #======================================================================
    # モデルの最適化アルゴリズム Optimizer を設定する。
    # Declare Optimizer.
    #======================================================================
    rnn1.optimizer( Adam( learning_rate = learning_rate1, beta1 = adam_beta1, beta2 = adam_beta2 ) )

    #======================================================================
    # モデルの初期化と学習(トレーニング)
    # ここまでの準備で, 実際に, 計算グラフ(有向グラフ)のオブジェクトを作成し,
    # プレースホルダを通じて, データを計算グラフ(有向グラフ)に供給する。
    # Initialize and train the model.
    #
    # ex) 計算グラフを初期化する方法の1つの例
    #     with tf.Session( graph = graph ) as session:
    #         ...
    #         session.run(...)
    #         ...
    #     session = tf.Session( graph = graph )  
    #     session.run(…)
    #======================================================================
    # TensorBoard 用のファイル(フォルダ)を作成
    #rnn1.write_tensorboard_graph()

    # fitting 処理を行う
    rnn1.fit( X_train, y_train )
    #rnn1.print( "after fitting" )

    #======================================================================
    # モデルの評価
    # (Optional) Evaluate the model.
    #======================================================================
    #---------------------------------------------------------
    # 損失関数を plot
    #---------------------------------------------------------
    plt.clf()
    plt.plot(
        range( rnn1._epochs ), rnn1._losses_train,
        label = 'RNN Encoder-Decoder - %s = [%d - %d - %d], learning_rate = %0.3f' % ( type(rnn1) , rnn1._n_inputLayer, rnn1._n_hiddenLayer, rnn1._n_outputLayer, learning_rate1 ) ,
        linestyle = '-',
        linewidth = 0.1,
        color = 'red'
    )
    plt.title( "loss / cross-entropy" )
    plt.legend( loc = 'best' )
    plt.ylim( ymin = 0.0 )
    plt.xlabel( "Epocs" )
    plt.grid()
    plt.tight_layout()
    
    MLPlot.saveFigure( fileName = "RNN_Encoder-Decoder_1-1.png" )
    plt.show()
    
    #---------------------------------------------------------
    # 予想値
    #---------------------------------------------------------
    # 予想値を取得
    predicts1 = rnn1.predict( X_test )
    print( "predicts1 :", predicts1 )
    
    # 正解率を取得
    accuracy_total1 = rnn1.accuracy( X_features, y_labels )
    accuracy_train1 = rnn1.accuracy( X_train, y_train )
    accuracy_test1 = rnn1.accuracy( X_test, y_test )
    print( "accuracy_total1 : {} / n_sample : {}".format( accuracy_total1,  len(X_features[:,0,0]) ) )
    print( "accuracy_train1 : {} / n_sample : {}".format( accuracy_train1,  len(X_train[:,0,0]) ) )
    print( "accuracy_test1 : {} / n_sample : {}".format( accuracy_test1,  len(X_test[:,0,0]) ) )

    #---------------------------------------------------------
    # 質問&応答処理
    #---------------------------------------------------------
    #print( "numpy.argmax( X_test[0,:,:], axis = -1 ) :", numpy.argmax( X_test[0,:,:], axis = -1 ) )
    # 質問文の数
    n_questions = min( 100, len(X_test[:,0,0]) )

    for q in range( n_questions ):
        answer = rnn1.question_answer_responce( question = X_test[q,:,:], dict_idx_to_str = dict_idx_to_str )
        
        # one-hot encoding → 対応する数値インデックス → 対応する文字に変換
        question = numpy.argmax( X_test[q,:,:], axis = -1 )
        question = "".join( dict_idx_to_str[i] for i in question )

        print( "-------------------------------" )
        print( "n_questions = {}".format( q ) )
        print( "Q : {}".format( question ) )
        print( "A : {}".format( answer ) )

        # 正解データ(教師データ)をone-hot encoding → 対応する数値インデックス → 対応する文字に変換
        target = numpy.argmax( y_test[q,:,:], axis = -1 )
        target = "".join( dict_idx_to_str[i] for i in target )

        if ( answer == target ):
            print( "T/F : T" )
        else:
            print( "T/F : F" )
        print( "-------------------------------" )


    #======================================================================
    # ハイパーパラメータのチューニング (Optional)
    #======================================================================


    #======================================================================
    # デプロイと新しい成果指標の予想 (Optional)
    #======================================================================


    print("Finish main()")
    return
Beispiel #2
0
def main():
    """
    TensorFlow を用いた LSTM によるノイズ付き sin 波形(時系列データ)からの波形の予想(生成)処理
    """
    print("Enter main()")

    # Reset graph
    #ops.reset_default_graph()

    # Session の設定
    #session = tf.Session()

    #======================================================================
    # データセットを読み込み or 生成
    # Import or generate data.
    #======================================================================
    T1 = 100                # ノイズ付き sin 波形の周期
    noize_size1 = 0.05      # ノイズ付き sin 波形のノイズ幅

    times = numpy.arange( 2.5 * T1 + 1 )    # 時間 t の配列 ( +1 は t=1~ のデータにするため)

    x_dat, y_dat = MLPreProcess.generate_sin_with_noize( t = times, T = T1, noize_size = noize_size1, seed = 12 )
    #print( "x_dat", x_dat )
    #print( "y_dat", y_dat )
    
    #======================================================================
    # データを変換、正規化
    # Transform and normalize data.
    # ex) data = tf.nn.batch_norm_with_global_normalization(...)
    #======================================================================
    # BPTT での計算負荷の関係上、時系列データを一定間隔に区切る
    len_sequences = len( x_dat )     # 全時系列データの長さ
    n_in_sequence = 25               # 1つの時系列データのシーケンスの長さ τ
    
    print( "len_sequences :", len_sequences )
    print( "n_in_sequence :", n_in_sequence )

    data = []       # 区切った時系列データの f(t=1~τ), f(t=2~τ+1), ... 値のリスト(各要素はベクトル)
    targets = []    # 区切った各 data の1つの要素 f(t) に対応する目的値 f(t+1) のリスト

    # サイズが τ で 
    # { f(t=1), f(t=2), ... , f(t=τ) }, { f(t=2), f(t=3), ... , f(t=τ+1) }, ... , { f(t-τ), f(t-τ+1), ... , f(t) }
    #  の合計 t - τ + 1 個のデータセットに対応したループ処理
    for i in range( 0, len_sequences - n_in_sequence ):
        data.append( y_dat[ i : i + n_in_sequence ] )
        targets.append( y_dat[ i + n_in_sequence ] )

    #print( "data[0].shape :", data[0].shape )
    #print( "targets[0].shape :", targets[0].shape )
    #print( "data :\n", data )
    #print( "targets :\n", targets )
    
    # 一般の次元のデータの場合にでも対応できるように、shape を
    # shape = (n_sample) → (n_data, n_in_sequence, 1) に reshape
    X_features = numpy.array( data ).reshape( len(data), n_in_sequence, 1 )
    y_labels = numpy.array( targets ).reshape( len(targets), 1 )

    print( "X_features.shape :", X_features.shape )
    print( "y_labels.shape :", y_labels.shape )
    print( "y_labels :", y_labels )
    
    #======================================================================
    # データセットをトレーニングデータ、テストデータ、検証データセットに分割
    #======================================================================
    X_train, X_test, y_train, y_test \
    = MLPreProcess.dataTrainTestSplit( X_input = X_features, y_input = y_labels, ratio_test = 0.1, input_random_state = 1 )

    print( "X_train.shape :", X_train.shape )
    print( "y_train.shape :", y_train.shape )
    print( "X_train :", X_train )
    print( "y_train :", y_train )

    #======================================================================
    # アルゴリズム(モデル)のパラメータを設定
    # Set algorithm parameters.
    # ex) learning_rate = 0.01  iterations = 1000
    #======================================================================
    learning_rate1 = 0.001
    adam_beta1 = 0.9        # For the Adam optimizer
    adam_beta2 = 0.999      # For the Adam optimizer

    rnn1 = RecurrentNNLSTM(
               session = tf.Session( config = tf.ConfigProto(log_device_placement=True) ),
               n_inputLayer = len( X_features[0][0] ),
               n_hiddenLayer = 50,
               n_outputLayer = len( y_labels[0] ),
               n_in_sequence = n_in_sequence,
               epochs = 500,
               batch_size = 10,
               eval_step = 1
           )
    """
    rnn2 = RecurrentNN(
               session = tf.Session( config = tf.ConfigProto(log_device_placement=True) ),
               n_inputLayer = len( X_features[0][0] ),
               n_hiddenLayer = 50,
               n_outputLayer = len( y_labels[0] ),
               n_in_sequence = n_in_sequence,
               epochs = 500,
               batch_size = 10,
               eval_step = 1
           )
    """
    rnn1.print( "after __init__()" )

    #======================================================================
    # 変数とプレースホルダを設定
    # Initialize variables and placeholders.
    # TensorFlow は, 損失関数を最小化するための最適化において,
    # 変数と重みベクトルを変更 or 調整する。
    # この変更や調整を実現するためには, 
    # "プレースホルダ [placeholder]" を通じてデータを供給(フィード)する必要がある。
    # そして, これらの変数とプレースホルダと型について初期化する必要がある。
    # ex) a_tsr = tf.constant(42)
    #     x_input_holder = tf.placeholder(tf.float32, [None, input_size])
    #     y_input_holder = tf.placeholder(tf.fload32, [None, num_classes])
    #======================================================================
    

    #======================================================================
    # モデルの構造を定義する。
    # Define the model structure.
    # ex) add_op = tf.add(tf.mul(x_input_holder, weight_matrix), b_matrix)
    #======================================================================
    rnn1.model()
    #rnn2.model()

    #======================================================================
    # 損失関数を設定する。
    # Declare the loss functions.
    #======================================================================
    rnn1.loss( L2Norm() )
    #rnn2.loss( L2Norm() )

    #======================================================================
    # モデルの最適化アルゴリズム Optimizer を設定する。
    # Declare Optimizer.
    #======================================================================
    rnn1.optimizer( Adam( learning_rate = learning_rate1, beta1 = adam_beta1, beta2 = adam_beta2 ) )
    #rnn2.optimizer( Adam( learning_rate = learning_rate1, beta1 = adam_beta1, beta2 = adam_beta2 ) )

    #======================================================================
    # モデルの初期化と学習(トレーニング)
    # ここまでの準備で, 実際に, 計算グラフ(有向グラフ)のオブジェクトを作成し,
    # プレースホルダを通じて, データを計算グラフ(有向グラフ)に供給する。
    # Initialize and train the model.
    #
    # ex) 計算グラフを初期化する方法の1つの例
    #     with tf.Session( graph = graph ) as session:
    #         ...
    #         session.run(...)
    #         ...
    #     session = tf.Session( graph = graph )  
    #     session.run(…)
    #======================================================================
    # TensorBoard 用のファイル(フォルダ)を作成
    rnn1.write_tensorboard_graph()

    # fitting 処理を行う
    rnn1.fit( X_train, y_train )
    #rnn2.fit( X_train, y_train )
    rnn1.print( "after fitting" )

    #======================================================================
    # モデルの評価
    # (Optional) Evaluate the model.
    #======================================================================
    # 時系列データの予想値を取得
    predicts1 = rnn1.predict( X_features )
    #predicts2 = rnn2.predict( X_features )
    print( "predicts1 :\n", predicts1 )

    #---------------------------------------------------------
    # 損失関数を plot
    #---------------------------------------------------------
    plt.clf()

    plt.plot(
        range( rnn1._epochs ), rnn1._losses_train,
        label = 'RNN-LSTM1 = [%d - %d - %d], learning_rate = %0.3f' % ( rnn1._n_inputLayer, rnn1._n_hiddenLayer, rnn1._n_outputLayer, learning_rate1 ) ,
        linestyle = '-',
        #linewidth = 2,
        color = 'red'
    )
    """
    plt.plot(
        range( rnn2._epochs ), rnn2._losses_train,
        label = 'RNN1 = [%d - %d - %d], learning_rate = %0.3f' % ( rnn2._n_inputLayer, rnn2._n_hiddenLayer, rnn2._n_outputLayer, learning_rate1 ) ,
        linestyle = '--',
        #linewidth = 2,
        color = 'blue'
    )
    """
    plt.title( "loss / L2 Norm (MSE)" )
    plt.legend( loc = 'best' )
    plt.ylim( ymin = 0.0 )
    plt.xlabel( "Epocs" )
    plt.grid()
    plt.tight_layout()
    
    MLPlot.saveFigure( fileName = "RNN-LSTM_1-1.png" )
    plt.show()


    #---------------------------------------------------------
    # 時系列データの予想値と元のノイズ付き sin 波形を plot
    #---------------------------------------------------------
    plt.clf()

    x_dat_with_noize, y_dat_with_noize = MLPreProcess.generate_sin_with_noize( t = times, T = T1, noize_size = noize_size1, seed = 12 )
    plt.plot(
        x_dat_with_noize, y_dat_with_noize,
        label = 'noize = %0.3f' % noize_size1,
        linestyle = '-',
        #linewidth = 2,
        color = 'black'
    )

    x_dat_without_noize, y_dat_without_noize = MLPreProcess.generate_sin_with_noize( t = times, T = T1, noize_size = 0, seed = 12 )
    plt.plot(
        x_dat_without_noize, y_dat_without_noize,
        label = 'without noize',
        linestyle = '--',
        #linewidth = 2,
        color = 'black'
    )

    plt.plot(
        x_dat, predicts1,
        label = 'predict1 : RNN-LSTM1 = [%d - %d - %d], learning_rate = %0.3f' % ( rnn1._n_inputLayer, rnn1._n_hiddenLayer, rnn1._n_outputLayer, learning_rate1 ),
        linestyle = '-',
        #linewidth = 2,
        color = 'red'
    )
    """
    plt.plot(
        x_dat, predicts2,
        label = 'predict2 : RNN1 = [%d - %d - %d], learning_rate = %0.3f' % ( rnn2._n_inputLayer, rnn2._n_hiddenLayer, rnn2._n_outputLayer, learning_rate1 ),
        linestyle = '--',
        #linewidth = 2,
        color = 'blue'
    )
    """
    plt.title( "time series / sin-wave with noize" )
    plt.legend( loc = 'best' )
    plt.ylim( [-1.10, 1.10] )
    plt.xlabel( "t [time]" )
    plt.grid()
    plt.tight_layout()
   
    MLPlot.saveFigure( fileName = "RNN-LSTM_1-2.png" )
    plt.show()

    #======================================================================
    # ハイパーパラメータのチューニング (Optional)
    #======================================================================


    #======================================================================
    # デプロイと新しい成果指標の予想 (Optional)
    #======================================================================


    print("Finish main()")
    return
def main():
    """
    TensorFlow を用いた DCGAN による MNIST データの自動生成
    """
    print("Enter main()")

    #======================================================================
    # コマンドライン引数
    #======================================================================
    """
    # パーサーの作成
    arg_parser = argparse.ArgumentParser(
                     prog = "main1.py",                   # プログラム名
                     usage = "TensorFlow を用いた DCGAN による MNIST データの自動生成",  # プログラムの利用方法
                     description = 'pre description',     # 引数のヘルプの前に表示する文
                     epilog = "epilog",                   # 引数のヘルプの後で表示する文
                     add_help = True                      # -h/–help オプションの追加
                 )

    # コマンドライン引数を追加
    # 位置引数 : 関数に対して必須となる引数
    # オプション引数: 与えても与えなくてもどちらでも良い引数
    # オプション引数には接頭辞「–」を付ける必要があり、実行時に引数を指定する場所はどこでも構いません。
    # 接頭辞「–」で短い略語を指定し、接頭辞「—-」で長い名称
    # オプション引数以外の引数は位置引数として扱われ、実行時の引数の位置は決まっています。
    arg_parser.add_argument( '--learning_rate', dest = 'learning_rate', type = float, default = 0.001 )

    # コマンドライン引数を解析する。
    arg_parser.parse_args()
    """

    #======================================================================
    # データセットを読み込み or 生成
    # Import or generate data.
    #======================================================================
    #======================================================================
    # データセットをトレーニングデータ、テストデータ、検証データセットに分割
    #======================================================================
    # MNIST データが格納されているフォルダへのパス
    mnist_path = "C:\Data\MachineLearning_DataSet\MNIST"

    X_train, y_train = MLPreProcess.load_mnist(mnist_path, "train")
    X_test, y_test = MLPreProcess.load_mnist(mnist_path, "t10k")

    # データは shape = [n_sample, image_width=28, image_height=28] の形状に reshape
    X_train = np.array([np.reshape(x, (28, 28)) for x in X_train])
    X_test = np.array([np.reshape(x, (28, 28)) for x in X_test])

    print("X_train.shape : ", X_train.shape)
    print("y_train.shape : ", y_train.shape)
    print("X_test.shape : ", X_test.shape)
    print("y_test.shape : ", y_test.shape)

    #print( "X_train : \n", X_train )
    #print( "y_train : \n", y_train )

    #======================================================================
    # データを変換、正規化
    # Transform and normalize data.
    # ex) data = tf.nn.batch_norm_with_global_normalization(...)
    #======================================================================
    # One -hot encoding
    #y_train_encoded = np.eye(10)[ y_train.astype(int) ]
    #y_test_encoded = np.eye(10)[ y_test.astype(int) ]
    """
    session = tf.Session()
    encode_holder = tf.placeholder(tf.int64, [None])
    y_oneHot_enoded_op = tf.one_hot( encode_holder, depth=10, dtype=tf.float32 ) # depth が 出力層のノード数に対応
    session.run( tf.global_variables_initializer() )
    y_train_encoded = session.run( y_oneHot_enoded_op, feed_dict = { encode_holder: y_train } )
    y_test_encoded = session.run( y_oneHot_enoded_op, feed_dict = { encode_holder: y_test } )
    print( "y_train_encoded.shape : ", y_train_encoded.shape )
    print( "y_train_encoded.dtype : ", y_train_encoded.dtype )
    print( "y_test_encoded.shape : ", y_test_encoded.shape )
    session.close()
    """

    #======================================================================
    # アルゴリズム(モデル)のパラメータを設定
    # Set algorithm parameters.
    # ex) learning_rate = 0.01  iterations = 1000
    #======================================================================
    epochs = 200
    #epochs = 5000
    #epochs = 7000
    #epochs = 20000

    eval_step = 50
    batch_size = 32
    learning_rate = 0.0001
    beta1 = 0.5
    beta2 = 0.99

    #======================================================================
    # 変数とプレースホルダを設定
    # Initialize variables and placeholders.
    # TensorFlow は, 損失関数を最小化するための最適化において,
    # 変数と重みベクトルを変更 or 調整する。
    # この変更や調整を実現するためには,
    # "プレースホルダ [placeholder]" を通じてデータを供給(フィード)する必要がある。
    # そして, これらの変数とプレースホルダと型について初期化する必要がある。
    # ex) a_tsr = tf.constant(42)
    #     x_input_holder = tf.placeholder(tf.float32, [None, input_size])
    #     y_input_holder = tf.placeholder(tf.fload32, [None, num_classes])
    #======================================================================
    # DCGAN クラスのオブジェクト生成
    dcgan = DeepConvolutionalGAN(
        session=tf.Session(config=tf.ConfigProto(log_device_placement=True)),
        epochs=epochs,
        batch_size=batch_size,
        eval_step=eval_step,
        image_height=28,  # 28 pixel
        image_width=28,  # 28 pixel
        n_channels=1,  # グレースケール
        n_G_deconv_featuresMap=[128, 64, 1],  # 
        n_D_conv_featuresMap=[1, 64, 128],  #
        n_labels=2)

    dcgan.print("after init")

    #======================================================================
    # モデルの構造を定義する。
    # Define the model structure.
    # ex) add_op = tf.add(tf.mul(x_input_holder, weight_matrix), b_matrix)
    #======================================================================
    dcgan.model()

    #======================================================================
    # 損失関数を設定する。
    # Declare the loss functions.
    #======================================================================
    dcgan.loss()
    dcgan.optimizer(nnOptimizerG=Adam(learning_rate=learning_rate,
                                      beta1=beta1,
                                      beta2=beta2),
                    nnOptimizerD=Adam(learning_rate=learning_rate,
                                      beta1=beta1,
                                      beta2=beta2))

    dcgan.print("after building model & loss & optimizer")

    # TensorBoard
    #dcgan.write_tensorboard_graph()

    #======================================================================
    # モデルの初期化と学習(トレーニング)
    # ここまでの準備で, 実際に, 計算グラフ(有向グラフ)のオブジェクトを作成し,
    # プレースホルダを通じて, データを計算グラフ(有向グラフ)に供給する。
    # Initialize and train the model.
    #
    # ex) 計算グラフを初期化する方法の1つの例
    #     with tf.Session( graph = graph ) as session:
    #         ...
    #         session.run(...)
    #         ...
    #     session = tf.Session( graph = graph )
    #     session.run(…)
    #======================================================================
    # トレーニングデータで fitting 処理
    dcgan.fit(X_train, y_train=None)

    # モデルの保存
    #dcgan.save_model()
    #dcgan.load_model()

    #======================================================================
    # モデルの評価
    # (Optional) Evaluate the model.
    #======================================================================
    #-------------------------------------------------------------------
    # トレーニング回数に対する loss 値の plot
    #-------------------------------------------------------------------
    # loss 値の list に対応させる x 軸データ用の list
    loss_axis_x = [(idx + 1) * eval_step
                   for idx in range(len(dcgan._losses_train))]
    #print( "loss_axis_x :", loss_axis_x )

    plt.clf()
    plt.plot(
        loss_axis_x,
        dcgan._losses_train,
        label=' loss (total) : train data',
        linestyle='-',
        #linewidth = 2,
        color='black')
    plt.plot(
        loss_axis_x,
        dcgan._losses_G_train,
        label=' loss (generator) : train data',
        linestyle='--',
        #linewidth = 2,
        color='red')
    plt.plot(
        loss_axis_x,
        dcgan._losses_D_train,
        label=' loss (discriminator) : train data',
        linestyle='--',
        #linewidth = 2,
        color='blue')
    plt.title("loss / sparse softmax cross-entory")
    plt.legend(loc='best')
    plt.xlim(1, epochs)
    #plt.ylim( [0, 1.05] )
    plt.xlabel("Epochs / batch_size = {}".format(batch_size))
    plt.grid()
    plt.tight_layout()

    #MLPlot.saveFigure( fileName = "GAN_DCGAN_1-1.png" )
    plt.savefig("GAN_DCGAN_1-1_epoch{}.png".format(epochs),
                dpi=300,
                bbox_inches="tight")
    #plt.show()

    #-------------------------------------------------------------------
    # 学習過程で生成しておいた画像の animation gif
    #-------------------------------------------------------------------
    fig = plt.figure(figsize=(4, 6))
    print("len(dcgan._images_evals[0])", len(dcgan._images_evals[0]))

    images = []
    for imgs in dcgan._images_evals:
        # row : 1
        subplot = fig.add_subplot(1, 1, 1)
        subplot.set_xticks([])
        subplot.set_yticks([])

        image = np.hstack(np.array(imgs))
        image = np.reshape(image, (28 * 4, 28 * 8))

        image = subplot.imshow(image, vmin=0, vmax=1, cmap=plt.cm.gray_r)
        images.append([image])

    ani = animation.ArtistAnimation(
        fig,
        images,
        interval=10  # ms 単位
    )

    ani.save('./output_image/DCGAN_fitting_epoch{}.gif'.format(epochs),
             writer='imagemagick',
             fps=100)
    plt.show()
    #-------------------------------------------------------------------
    # 学習済み DCGAN に対し、入力ノイズ自動画像生成
    #-------------------------------------------------------------------
    # Generator に入力する初期ノイズ
    input_noize1 = np.random.rand(batch_size, 64) * 2.0 - 1.0
    inputs_noize_tsr1 = tf.constant(np.array(input_noize1), dtype=tf.float32)

    # result : 0.0 ~ 1.0
    result1 = dcgan._session.run(
        dcgan.generator(input=inputs_noize_tsr1, reuse=True))

    images1 = []
    for i in range(result1.shape[0]):
        images1.append(result1[i, :, :, 0])

    fig = plt.figure(figsize=(4, 8))
    k = 0
    for i in range(8):
        for j in range(4):
            k += 1
            subplot = fig.add_subplot(4, 8, k)
            subplot.set_xticks([])
            subplot.set_yticks([])
            subplot.imshow(images1[k - 1], vmin=0, vmax=1, cmap=plt.cm.gray_r)
    plt.savefig("GAN_DCGAN_1-2_epoch{}.png".format(epochs),
                dpi=300,
                bbox_inches="tight")

    #-------------------------------------------------------------------
    # 学習済み DCGAN に対し、入力ノイズを動かし Animation gif
    #-------------------------------------------------------------------
    # Generator に入力する初期ノイズ
    input_noize = np.random.rand(3, 64) * 2.0 - 1.0

    morphing_inputs = []

    # 球の表面上の回転
    theta1, theta2 = 0, 0
    for _ in range(32):  # batch_size
        theta1 += 2 * np.pi / 32 * 2
        theta2 += 2 * np.pi / 32
        morphing_inputs.append(
            np.cos(theta1) * input_noize[0] \
            + np.sin(theta1)*( np.cos(theta2)*input_noize[1] + np.sin(theta2)*input_noize[2] )
        )

    inputs_noize_tsr = tf.constant(np.array(morphing_inputs), dtype=tf.float32)

    # result : 0.0 ~ 1.0
    result = dcgan._session.run(
        dcgan.generator(input=inputs_noize_tsr, reuse=True))

    images = []
    fig = plt.figure(figsize=(4, 4))
    for i in range(result.shape[0]):
        subplot = fig.add_subplot(1, 1, 1)
        subplot.set_xticks([])
        subplot.set_yticks([])
        image = subplot.imshow(result[i, :, :, 0],
                               vmin=0,
                               vmax=1,
                               cmap=plt.cm.gray_r)
        images.append([image
                       ])  # i=63 : ValueError: outfile must be *.htm or *.html

    ani = animation.ArtistAnimation(
        fig,
        images,
        interval=10  # ms 単位
    )

    ani.save('./output_image/DCGAN_morphing1_epoch{}.gif'.format(epochs),
             writer='imagemagick',
             fps=100)

    #---------------------------------------
    # Generator に入力する初期ノイズ
    input_noize = np.random.rand(3, 64) * 2.0 - 1.0

    morphing_inputs = []

    # 球の表面上の回転
    theta1, theta2 = 0, 0
    for _ in range(32):  # batch_size
        theta1 += 2 * np.pi / 32
        theta2 += 2 * np.pi / 32
        morphing_inputs.append(
            np.cos(theta1) * input_noize[0] \
            + np.sin(theta1)*( np.cos(theta2)*input_noize[1] + np.sin(theta2)*input_noize[2] )
        )

    inputs_noize_tsr = tf.constant(np.array(morphing_inputs), dtype=tf.float32)

    # result : 0.0 ~ 1.0
    result = dcgan._session.run(
        dcgan.generator(input=inputs_noize_tsr, reuse=True))

    images = []
    fig = plt.figure(figsize=(4, 4))
    for i in range(result.shape[0]):
        subplot = fig.add_subplot(1, 1, 1)
        subplot.set_xticks([])
        subplot.set_yticks([])
        image = subplot.imshow(result[i, :, :, 0],
                               vmin=0,
                               vmax=1,
                               cmap=plt.cm.gray_r)
        images.append([image
                       ])  # i=63 : ValueError: outfile must be *.htm or *.html

    ani = animation.ArtistAnimation(
        fig,
        images,
        interval=10  # ms 単位
    )

    ani.save('./output_image/DCGAN_morphing2_epoch{}.gif'.format(epochs),
             writer='imagemagick',
             fps=100)
    plt.show()

    #======================================================================
    # ハイパーパラメータのチューニング (Optional)
    #======================================================================

    #======================================================================
    # デプロイと新しい成果指標の予想 (Optional)
    #======================================================================

    print("Finish main()")
    return
Beispiel #4
0
def main():
    """
    TensorFlow を用いた RNN によるテキストデータからのスパムの確率予想処理
    """
    print("Enter main()")

    # Reset graph
    #ops.reset_default_graph()

    # Session の設定
    #session = tf.Session()

    #======================================================================
    # データセットを読み込み or 生成
    # Import or generate data.
    #======================================================================
    # SMS Spam Collection データセットのファイルへのパス
    spam_datset_path = "C:\Data\MachineLearning_DataSet\SMS_Spam_Collection\smsspamcollection\SMSSpamCollection.txt"

    # SMS Spam Collection データセットからテキストデータを読み込み、取得する。
    text_data_features, text_data_labels = MLPreProcess.load_sms_spam_collection( path = spam_datset_path, bCleaning = True )
    print( "len( text_data_features ) :", len( text_data_features ) )   # len( text_data_features ) : 5573
    print( "len( text_data_labels ) :", len( text_data_labels ) )       # len( text_data_labels ) : 5573

    #======================================================================
    # データを変換、正規化
    # Transform and normalize data.
    # ex) data = tf.nn.batch_norm_with_global_normalization(...)
    #======================================================================
    # テキスト情報を数値インデックスのリストに変換する。
    X_features, n_vocab = MLPreProcess.text_vocabulary_processing( text_data = text_data_features, n_max_in_sequence = 25, min_word_freq = 10 )
    y_labels = numpy.array( [1 if label_str=='ham' else 0 for label_str in text_data_labels] )

    print( "X_features.shape :", X_features.shape )     # X_features.shape : (5573, 25)
    print( "y_labels.shape :", y_labels.shape )         # y_labels.shape : (5573,)
    print( "n_vocab", n_vocab )                         # n_vocab 934

    # データをシャッフルする。
    shuffled_idx = numpy.random.permutation( numpy.arange( len(y_labels) ) )
    X_features_shuffled = X_features[ shuffled_idx ]
    y_labels_shuffled = y_labels[ shuffled_idx ]
    
    print( "X_features_shuffled.shape :", X_features_shuffled.shape )   # X_features_shuffled.shape : (5573, 25)
    print( "y_labels_shuffled.shape :", y_labels_shuffled.shape )       # y_labels_shuffled.shape : (5573,)

    #======================================================================
    # データセットをトレーニングデータ、テストデータ、検証データセットに分割
    #======================================================================
    X_train, X_test, y_train, y_test \
    = MLPreProcess.dataTrainTestSplit( X_input = X_features, y_input = y_labels, ratio_test = 0.2, input_random_state = 1 )

    print( "X_train.shape :", X_train.shape )   # X_train.shape : (4458, 25)
    print( "y_train.shape :", y_train.shape )   # y_train.shape : (4458,)
    print( "X_train :", X_train )               # [[ 12 324  43 ...,  49  11   0] [469 851 418 ...,   0   0   0] ... [ 11  93 440 ...,   0   0   0]]
    print( "y_train :", y_train )               # [1 0 1 ..., 1 0 1]

    #======================================================================
    # アルゴリズム(モデル)のパラメータを設定
    # Set algorithm parameters.
    # ex) learning_rate = 0.01  iterations = 1000
    #======================================================================
    learning_rate1 = 0.0005
    learning_rate2 = 0.0001
    adam_beta1 = 0.9        # For the Adam optimizer
    adam_beta2 = 0.999      # For the Adam optimizer

    rnn1 = RecurrectNNLanguageModel(
               session = tf.Session( config = tf.ConfigProto(log_device_placement=True) ),
               n_inputLayer = 1,
               n_hiddenLayer = 10,
               n_outputLayer = 2,
               n_in_sequence = 25,
               n_vocab = n_vocab,           # 934
               n_in_embedding_vec = 50,
               epochs = 5000,
               batch_size = 250,
               eval_step = 1
           )
    rnn1.print( "after __init__()" )

    #======================================================================
    # 変数とプレースホルダを設定
    # Initialize variables and placeholders.
    # TensorFlow は, 損失関数を最小化するための最適化において,
    # 変数と重みベクトルを変更 or 調整する。
    # この変更や調整を実現するためには, 
    # "プレースホルダ [placeholder]" を通じてデータを供給(フィード)する必要がある。
    # そして, これらの変数とプレースホルダと型について初期化する必要がある。
    # ex) a_tsr = tf.constant(42)
    #     x_input_holder = tf.placeholder(tf.float32, [None, input_size])
    #     y_input_holder = tf.placeholder(tf.fload32, [None, num_classes])
    #======================================================================
    

    #======================================================================
    # モデルの構造を定義する。
    # Define the model structure.
    # ex) add_op = tf.add(tf.mul(x_input_holder, weight_matrix), b_matrix)
    #======================================================================
    rnn1.model()

    #======================================================================
    # 損失関数を設定する。
    # Declare the loss functions.
    #======================================================================
    rnn1.loss( SparseSoftmaxCrossEntropy() )
    
    #======================================================================
    # モデルの最適化アルゴリズム Optimizer を設定する。
    # Declare Optimizer.
    #======================================================================
    #rnn1.optimizer( RMSProp( learning_rate = learning_rate1 ) )
    rnn1.optimizer( Adam( learning_rate = learning_rate1, beta1 = adam_beta1, beta2 = adam_beta2 ) )

    #======================================================================
    # モデルの初期化と学習(トレーニング)
    # ここまでの準備で, 実際に, 計算グラフ(有向グラフ)のオブジェクトを作成し,
    # プレースホルダを通じて, データを計算グラフ(有向グラフ)に供給する。
    # Initialize and train the model.
    #
    # ex) 計算グラフを初期化する方法の1つの例
    #     with tf.Session( graph = graph ) as session:
    #         ...
    #         session.run(...)
    #         ...
    #     session = tf.Session( graph = graph )  
    #     session.run(…)
    #======================================================================
    # TensorBoard 用のファイル(フォルダ)を作成
    rnn1.write_tensorboard_graph()
    
    # fitting 処理
    rnn1.fit( X_train, y_train )
    rnn1.print( "after fitting" )

    #======================================================================
    # モデルの評価
    # (Optional) Evaluate the model.
    #======================================================================

    # 時系列データの予想値を取得
    predicts1 = rnn1.predict( X_test )
    print( "predicts1 :", predicts1 )
    print( "len( predicts1 ) :", len( predicts1 ) )
    
    #---------------------------------------------------------
    # 正解率の算出
    #---------------------------------------------------------
    # テストデータでの正解率
    accuracy1 = rnn1.accuracy( X_test, y_test )
    print( "accuracy1 [test data] : %0.3f" % accuracy1 )
 
    print( "accuracy1 labels [test data]" )
    accuracys1 = rnn1.accuracy_labels( X_test, y_test )
    for i in range( len(accuracys1) ):
        print( "label %d : %.3f" % ( i, accuracys1[i] ) )

    #---------------------------------------------------------
    # 損失関数を plot
    #---------------------------------------------------------
    plt.clf()

    plt.plot(
        range( rnn1._epochs ), rnn1._losses_train,
        label = 'RNNLM1 = [%d - %d - %d], learning_rate = %0.4f' % ( rnn1._n_inputLayer, rnn1._n_hiddenLayer, rnn1._n_outputLayer, learning_rate1 ) ,
        linestyle = '-',
        linewidth = 0.5,
        color = 'red'
    )
    plt.title( "loss / sparse softmax cross-entropy" )
    plt.legend( loc = 'best' )
    plt.ylim( [0, 1.05] )
    plt.xlabel( "Epocs" )
    plt.grid()
    plt.tight_layout()
    
    MLPlot.saveFigure( fileName = "RNNLM_2-1.png" )
    plt.show()
    
    #======================================================================
    # ハイパーパラメータのチューニング (Optional)
    #======================================================================


    #======================================================================
    # デプロイと新しい成果指標の予想 (Optional)
    #======================================================================


    print("Finish main()")
    return
def main():
    """
    TensorFlow を用いた Many-to-one な RNN (LSTM 使用)によるIMDb映画評論の感情分析
    """
    print("Enter main()")

    # Reset graph
    #ops.reset_default_graph()

    #======================================================================
    # データセットを読み込み or 生成
    # Import or generate data.
    #======================================================================
    #SaveCsvFileFromIMDbDataset( "C:\Data\MachineLearning_DataSet\\aclImdb" )
    dfIMb = pd.read_csv("movie_data.csv", encoding="utf-8")

    counts = Counter()

    #-------------------------------------------------
    # クリーニング & 出現単語カウント処理
    #-------------------------------------------------
    for (i, review) in enumerate(dfIMb["review"]):
        # string.punctuation : 文字と文字の間の句読点、括弧などをまとめたもの
        # 置換表現で「!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~」等
        punctuation = string.punctuation

        # sep.join(seq) : sepを区切り文字として、seqを連結してひとつの文字列にする。
        # "".join(...) : list<str> → 1つの str に変換
        # " " + str + " " : 空白スペースで分割
        text = "".join([
            str if str not in punctuation else " " + str + " "
            for str in review
        ])

        # リスト中の大文字→小文字に変換
        text = text.lower()

        # loc() : 行ラベル、 列ラベルで pandas DataFrame のデータを参照
        dfIMb.loc[i, "review"] = text

        # Counter.update() : 辞書オブジェクトに辞書オブジェクトを後ろから連結。
        # string.split(“ 区切り文字 ”) : 区切り文字で区切られたリストを得る
        counts.update(text.split())

    # counts Counter({'the': 667950, '.': 650520, ',': 544818, 'and': 324383, 'a': 322941, 'of': 289412, ...
    # 'japanes': 1, 'germinates': 1, 'aspidistra': 1, 'bonhomie': 1, 'horlicks': 1})
    #print( "counts", counts)

    #======================================================================
    # データを変換、正規化
    # Transform and normalize data.
    # ex) data = tf.nn.batch_norm_with_global_normalization(...)
    #======================================================================
    #-------------------------------------------------
    # 読み込みデータの単語 → 整数型へのマッピング処理
    #-------------------------------------------------
    # key = counts.get(単語の出現回数)に従ってソート
    word_counts = sorted(counts, key=counts.get, reverse=True)
    print("word_counts", word_counts[:5])  # ['the', '.', ',', 'and', 'a']

    dict_word2int = {word: ii for (ii, word) in enumerate(word_counts, 1)}

    mapped_reviews = []  # レビュー文を(出現単語回数の)数値インデックス情報に変換したデータ
    for review in dfIMb["review"]:
        mapped_reviews.append([dict_word2int[word] for word in review.split()])

    print("mapped_review", mapped_reviews[:10]
          )  # mapped_review [[15, 5646, 3, 1, 2160, 3977, 26959 ...

    #-------------------------------------------------
    # Zero padding
    #-------------------------------------------------
    sequence_length = 200  # シーケンス長(RNN の T に対応)
    sequences = np.zeros(shape=(len(mapped_reviews), sequence_length),
                         dtype=int)

    for (i, row) in enumerate(mapped_reviews):
        review_arr = np.array(row)
        sequences[i,
                  -len(row):] = review_arr[-sequence_length:]  # 配列の右側から詰めていく

    #======================================================================
    # データセットをトレーニングデータ、テストデータ、検証データセットに分割
    #======================================================================
    X_train = sequences[:25000, :]
    y_train = dfIMb.loc[:25000, "sentiment"].values

    X_test = sequences[25000:, :]
    y_test = dfIMb.loc[25000:, "sentiment"].values

    #print( "n_samples [total] :", sequences.shape[0] )
    print("n_samples [train] :", X_train.shape[0])
    print("n_samples [test] :", X_test.shape[0])

    #======================================================================
    # アルゴリズム(モデル)のパラメータを設定
    # Set algorithm parameters.
    # ex) learning_rate = 0.01  iterations = 1000
    #======================================================================
    n_words = max(list(dict_word2int.values())) + 1
    print("n_words :", n_words)

    learning_rate1 = 0.001
    adam_beta1 = 0.9  # For the Adam optimizer
    adam_beta2 = 0.999  # For the Adam optimizer

    rnn = Many2OneMultiRNNLSTM(
        session=tf.Session(),
        n_hiddenLayer=128,  # 1つの LSTM ブロック中に集約されている隠れ層のノード数
        n_MultiRNN=1,
        n_in_sequence_encoder=sequence_length,  # エンコーダー側のシーケンス長 / 
        n_vocab=n_words,  # 単語数(埋め込み行列の行数)
        epochs=40,
        batch_size=100,
        eval_step=1,
        save_step=500)

    #======================================================================
    # 変数とプレースホルダを設定
    # Initialize variables and placeholders.
    # TensorFlow は, 損失関数を最小化するための最適化において,
    # 変数と重みベクトルを変更 or 調整する。
    # この変更や調整を実現するためには,
    # "プレースホルダ [placeholder]" を通じてデータを供給(フィード)する必要がある。
    # そして, これらの変数とプレースホルダと型について初期化する必要がある。
    # ex) a_tsr = tf.constant(42)
    #     x_input_holder = tf.placeholder(tf.float32, [None, input_size])
    #     y_input_holder = tf.placeholder(tf.fload32, [None, num_classes])
    #======================================================================

    #======================================================================
    # モデルの構造を定義する。
    # Define the model structure.
    # ex) add_op = tf.add(tf.mul(x_input_holder, weight_matrix), b_matrix)
    #======================================================================
    rnn.model()

    #======================================================================
    # 損失関数を設定する。
    # Declare the loss functions.
    #======================================================================
    rnn.loss(SigmoidCrossEntropy())

    #======================================================================
    # モデルの最適化アルゴリズム Optimizer を設定する。
    # Declare Optimizer.
    #======================================================================
    rnn.optimizer(
        Adam(learning_rate=learning_rate1, beta1=adam_beta1, beta2=adam_beta2))

    #======================================================================
    # モデルの初期化と学習(トレーニング)
    # ここまでの準備で, 実際に, 計算グラフ(有向グラフ)のオブジェクトを作成し,
    # プレースホルダを通じて, データを計算グラフ(有向グラフ)に供給する。
    # Initialize and train the model.
    #
    # ex) 計算グラフを初期化する方法の1つの例
    #     with tf.Session( graph = graph ) as session:
    #         ...
    #         session.run(...)
    #         ...
    #     session = tf.Session( graph = graph )
    #     session.run(…)
    #======================================================================
    # TensorBoard 用のファイル(フォルダ)を作成
    #rnn.write_tensorboard_graph()

    rnn.print("before fitting")
    rnn.fit(X_train, y_train)

    #======================================================================
    # モデルの評価
    # (Optional) Evaluate the model.
    #======================================================================
    #---------------------------------------------------------
    # 損失関数を plot
    #---------------------------------------------------------
    plt.clf()
    plt.plot(range(len(rnn._losses_train)),
             rnn._losses_train,
             label='RNN - %s = [%d - %d], learning_rate = %0.3f' %
             (type(rnn), rnn._n_hiddenLayer, rnn._n_MultiRNN, learning_rate1),
             linestyle='-',
             linewidth=0.2,
             color='red')
    plt.title("loss / Sigmoid Cross Entropy")
    plt.legend(loc='best')
    plt.ylim(ymin=0.0)
    plt.xlabel("minibatch iteration")
    plt.grid()
    plt.tight_layout()

    MLPlot.saveFigure(fileName="RNN-LSTM_3-1.png")
    plt.show()

    #---------------------------------------------------------
    # 正解率を predict
    #---------------------------------------------------------
    #pred = rnn.predict( X_test )
    #print( "pred :", pred )

    accuracy_train = rnn.accuracy(X_train, y_train)
    accuracy_test = rnn.accuracy(X_test, y_test)

    print("accuracy [train] :", accuracy_train)
    print("accuracy [test] :", accuracy_test)

    print("Finish main()")

    return
def main():
    """
    TensorFlow を用いた CNN-StyleNet / NeuralStyle(ニューラルスタイル)による画像生成処理
    """
    print("Enter main()")

    # Reset graph
    #ops.reset_default_graph()

    # Session の設定
    #session = tf.Session()

    #======================================================================
    # データセットを読み込み or 生成
    # Import or generate data.
    #======================================================================

    #======================================================================
    # データを変換、正規化
    # Transform and normalize data.
    # ex) data = tf.nn.batch_norm_with_global_normalization(...)
    #======================================================================

    #======================================================================
    # データセットをトレーニングデータ、テストデータ、検証データセットに分割
    #======================================================================

    #======================================================================
    # アルゴリズム(モデル)のパラメータを設定
    # Set algorithm parameters.
    # ex) learning_rate = 0.01  iterations = 1000
    #======================================================================
    image_content_path1 = "C:\Data\MachineLearning_DataSet\CNN-StyleNet\image_content\\neko-sensei.jpg"
    image_style_path1 = "C:\Data\MachineLearning_DataSet\CNN-StyleNet\image_style\starry_night.jpg"
    learning_rate1 = 0.01
    adam_beta1 = 0.9  # For the Adam optimizer
    adam_beta2 = 0.999  # For the Adam optimizer

    #======================================================================
    # 変数とプレースホルダを設定
    # Initialize variables and placeholders.
    # TensorFlow は, 損失関数を最小化するための最適化において,
    # 変数と重みベクトルを変更 or 調整する。
    # この変更や調整を実現するためには,
    # "プレースホルダ [placeholder]" を通じてデータを供給(フィード)する必要がある。
    # そして, これらの変数とプレースホルダと型について初期化する必要がある。
    # ex) a_tsr = tf.constant(42)
    #     x_input_holder = tf.placeholder(tf.float32, [None, input_size])
    #     y_input_holder = tf.placeholder(tf.fload32, [None, num_classes])
    #======================================================================
    styleNet1 = CNNStyleNet(
        image_content_path=image_content_path1,
        image_style_path=image_style_path1,
        vgg_mat_file=
        "C:\Data\MachineLearning_DataSet\CNN-StyleNet\imagenet-vgg-verydeep-19.mat",
        session=tf.Session(config=tf.ConfigProto(log_device_placement=True)),
        epochs=10000,
        eval_step=50,
        weight_image_content=200.0,
        weight_image_style=200.0,
        weight_regularization=100,
        n_strides=1,
        n_pool_wndsize=2,
        n_pool_strides=2)

    styleNet1.print("")

    #======================================================================
    # モデルの構造を定義する。
    # Define the model structure.
    # ex) add_op = tf.add(tf.mul(x_input_holder, weight_matrix), b_matrix)
    #======================================================================
    styleNet1.model()
    styleNet1.print("after model()")

    #======================================================================
    # 損失関数を設定する。
    # Declare the loss functions.
    #======================================================================
    styleNet1.loss()

    #======================================================================
    # モデルの最適化アルゴリズム Optimizer を設定する。
    # Declare Optimizer.
    #======================================================================
    styleNet1.optimizer(
        Adam(learning_rate=learning_rate1, beta1=adam_beta1, beta2=adam_beta2))
    #styleNet1._session.run( tf.global_variables_initializer() )
    #styleNet1.optimizer( GradientDecent( learning_rate = learning_rate1 ) )

    # TensorBoard 用のファイル(フォルダ)を作成
    styleNet1.write_tensorboard_graph()

    #======================================================================
    # モデルの初期化と学習(トレーニング)
    # ここまでの準備で, 実際に, 計算グラフ(有向グラフ)のオブジェクトを作成し,
    # プレースホルダを通じて, データを計算グラフ(有向グラフ)に供給する。
    # Initialize and train the model.
    #
    # ex) 計算グラフを初期化する方法の1つの例
    #     with tf.Session( graph = graph ) as session:
    #         ...
    #         session.run(...)
    #         ...
    #     session = tf.Session( graph = graph )
    #     session.run(…)
    #======================================================================
    styleNet1.run()

    #======================================================================
    # モデルの評価
    # (Optional) Evaluate the model.
    #======================================================================
    #styleNet1.show_output_image()
    #styleNet1.save_output_image( "", "CNN-StyleNet_output_image_1.png" )
    #styleNet1.save_output_image_gif( "", "CNN-StyleNet_output_image_1.gif" )

    #-------------------------------------------------------------------
    # トレーニング回数に対する loss 値の plot
    #-------------------------------------------------------------------
    plt.clf()
    plt.plot(
        range(len(styleNet1._losses_train)),
        styleNet1._losses_train,
        label="losses",
        linestyle='-',
        #linewidth = 2,
        color='black')
    plt.plot(
        range(len(styleNet1._losses_content_train)),
        styleNet1._losses_content_train,
        label="losses_content",
        linestyle='--',
        #linewidth = 2,
        color='red')
    plt.plot(
        range(len(styleNet1._losses_style_train)),
        styleNet1._losses_style_train,
        label="losses_style",
        linestyle='--',
        #linewidth = 2,
        color='blue')
    plt.plot(
        range(len(styleNet1._losses_total_var_train)),
        styleNet1._losses_total_var_train,
        label="losses_total_var",
        linestyle='--',
        #linewidth = 2,
        color='green')
    plt.title("loss : AdamOptimizer")
    plt.legend(loc='best')
    #plt.ylim( [0, 1.05] )
    plt.xlabel("Epocs %d / eval_step %d" %
               (styleNet1._epochs, styleNet1._eval_step))
    plt.tight_layout()

    plt.savefig("CNN_StyleNet_1-1.png", dpi=300, bbox_inches="tight")
    plt.show()

    #======================================================================
    # ハイパーパラメータのチューニング (Optional)
    #======================================================================

    #======================================================================
    # デプロイと新しい成果指標の予想 (Optional)
    #======================================================================

    print("Finish main()")
    return