├── .gitignore ├── CNN_StyleNet_TensorFlow ├── CNNStyleNet.py ├── NNActivation.py ├── NNLoss.py ├── NNOptimizer.py ├── README.md └── main1.py ├── CNN_TensorFlow ├── ConvolutionalNN.py ├── MLPlot.py ├── MLPreProcess.py ├── MultilayerPerceptron.py ├── NNActivation.py ├── NNLoss.py ├── NNOptimizer.py ├── NeuralNetworkBase.py ├── README.md ├── main1.py ├── main1_1.py └── main2.py ├── GAN_DCGAN_TensorFlow ├── DeepConvolutionalGAN.py ├── MLPlot.py ├── MLPreProcess.py ├── NNActivation.py ├── NNLoss.py ├── NNOptimizer.py ├── NeuralNetworkBase.py ├── README.md └── main1.py ├── MultilayerPerceptron_TensorFlow ├── MLPlot.py ├── MLPreProcess.py ├── MultilayerPerceptron.py ├── NNActivation.py ├── NNLoss.py ├── NNOptimizer.py ├── NeuralNetworkBase.py ├── README.md ├── main1.py ├── main2.py └── main3.py ├── ObjectDetection_SSD_TensorFlow ├── README.md ├── VOC2007.pkl ├── main1.py ├── main2.py ├── model │ ├── BBoxMatcher.py │ ├── BaseNetwork.py │ ├── BoundingBox.py │ ├── DefaultBox.py │ ├── NNActivation.py │ ├── NNLoss.py │ ├── NNOptimizer.py │ ├── NeuralNetworkBase.py │ ├── SingleShotMultiBoxDetector.py │ ├── VGG16Network.py │ └── __init__.py └── util │ ├── MLPlot.py │ ├── MLPreProcess.py │ └── __init__.py ├── ProcessingForMachineLearning_TensorFlow ├── MLPlot.py ├── README.md ├── main1.py ├── main2.py ├── main3.py ├── main4.py ├── main5.py └── main_templete.py ├── Processing_TensorFlow ├── README.md ├── TensorBoard │ ├── TensorBoard_graph_PlaceHolder-Identity.png │ ├── TensorBoard_graph_Variable-Zero.png │ ├── events.out.tfevents.1504551219.THINKPAD-T520 │ └── events.out.tfevents.1504555085.THINKPAD-T520 ├── main1.py ├── main2.py ├── main3.py ├── main4.py ├── main5.py ├── main7.py ├── main8.py └── main9.py ├── README.md ├── RNN_Encoder-Decoder_TensorFlow ├── MLPlot.py ├── MLPreProcess.py ├── NNActivation.py ├── NNLoss.py ├── NNOptimizer.py ├── NeuralNetworkBase.py ├── README.md ├── RecurrectNNEncoderDecoderEmbeddingLSTM.py ├── RecurrectNNEncoderDecoderLSTM.py ├── main1.py └── main2.py ├── RNN_LSTM_TensorFlow ├── MLPlot.py ├── MLPreProcess.py ├── Many2OneMultiRNNLSTM.py ├── NNActivation.py ├── NNLoss.py ├── NNOptimizer.py ├── NeuralNetworkBase.py ├── README.md ├── RecurrentNN.py ├── RecurrentNNLSTM.py ├── main1.py ├── main2.py └── main3.py ├── RNN_TensorFlow ├── MLPlot.py ├── MLPreProcess.py ├── NNActivation.py ├── NNLoss.py ├── NNOptimizer.py ├── NeuralNetworkBase.py ├── README.md ├── RecurrectNNLanguageModel.py ├── RecurrentNN.py ├── main1.py └── main2.py ├── Seq2Seq_RNN_Encoder-Decoder_TensorFlow ├── MLPlot.py ├── MLPreProcess.py ├── NNActivation.py ├── NNLoss.py ├── NNOptimizer.py ├── NeuralNetworkBase.py ├── README.md ├── RecurrectNNEncoderDecoderLSTM.py ├── Seq2SeqMultiRNNLSTM.py ├── _Old │ ├── Seq2SeqRNNEncoderDecoderLSTM.py │ └── main2.py ├── main1.py └── main3.py └── dataset.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | -------------------------------------------------------------------------------- /CNN_StyleNet_TensorFlow/NNActivation.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/21] : 新規作成 7 | [17/11/18] : NNActivation クラスの仕様変更。NNActivation クラスの子クラス定義 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNActivation( object ): 19 | """ 20 | ニューラルネットワークの活性化関数を表すクラス 21 | 実際の活性化関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _activate_op : 活性化関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Activation_op" ): 34 | self._activate_op = None 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNActivation" ) 41 | print( self ) 42 | print( str ) 43 | print( "_activate_op :", self._activate_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | def activate( self, input, node_name = "Activation_op" ): 49 | """ 50 | 活性化関数のオペレーターを返す。 51 | 52 | [Input] 53 | input : Operator or placeholder 54 | 活性化関数の入力となる Operatore、又は placeholder 55 | 56 | [Output] 57 | 活性化関数のオペレーター 58 | """ 59 | return self._activate_op 60 | 61 | 62 | class Sigmoid( NNActivation ): 63 | """ 64 | シグモイド関数の活性化関数 65 | NNActivation クラスの子クラスとして定義 66 | """ 67 | def __init__( self, node_name = "Activate_Sigmoid_op" ): 68 | self._activate_op = None 69 | self._node_name = node_name 70 | 71 | return 72 | 73 | def activate( self, input, node_name = "Activate_Sigmoid_op" ): 74 | self._activate_op = tf.nn.sigmoid( input, name = node_name ) 75 | self._node_name = node_name 76 | 77 | return self._activate_op 78 | 79 | 80 | class Relu( NNActivation ): 81 | """ 82 | Relu 関数の活性化関数 83 | NNActivation クラスの子クラスとして定義 84 | """ 85 | def __init__( self, node_name = "Activate_Relu_op" ): 86 | self._activate_op = None 87 | self._node_name = node_name 88 | 89 | return 90 | 91 | def activate( self, input, node_name = "Activate_Relu_op" ): 92 | self._activate_op = tf.nn.relu( input, name = node_name ) 93 | self._node_name = node_name 94 | 95 | return self._activate_op 96 | 97 | 98 | class Softmax( NNActivation ): 99 | """ 100 | softmax 関数の活性化関数 101 | NNActivation クラスの子クラスとして定義 102 | """ 103 | def __init__( self, node_name = "Activate_Softmax_op" ): 104 | self._activate_op = None 105 | self._node_name = node_name 106 | 107 | return 108 | 109 | def activate( self, input, node_name = "Activate_Softmax_op" ): 110 | self._activate_op = tf.nn.softmax( input, name = node_name ) 111 | self._node_name = node_name 112 | 113 | return self._activate_op 114 | 115 | -------------------------------------------------------------------------------- /CNN_StyleNet_TensorFlow/NNLoss.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/xx/xx] : 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | class NNLoss( object ): 18 | """ 19 | ニューラルネットワークの損失関数(評価関数、誤差関数)を表すクラス 20 | 実際の損失関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 21 | ------------------------------------------------------------------------------------------------ 22 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 23 | _loss_op : 損失関数の Operater 24 | _node_name : str 25 | この Operator ノードの名前 26 | 27 | [protedted] protedted な使用法を想定 28 | 29 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 30 | 31 | """ 32 | def __init__( self, node_name = "Loss_op" ): 33 | self._loss_op = loss( t_holder, y_out_op, node_name ) 34 | self._node_name = node_name 35 | 36 | return 37 | 38 | def print( str ): 39 | print( "NNLoss" ) 40 | print( self ) 41 | print( str ) 42 | print( "_loss_op :", self._loss_op ) 43 | print( "_node_name :", self._node_name ) 44 | 45 | return 46 | 47 | 48 | def loss( self, t_holder, y_out_op ): 49 | """ 50 | 損失関数のオペレーターを返す。 51 | 52 | [Input] 53 | _t_holder : Placeholder 54 | 教師データの Placeholder 55 | _y_out_op : Operator 56 | 出力の Operator 57 | 58 | [Output] 59 | 損失関数のオペレーター 60 | """ 61 | self._loss_op = None 62 | 63 | return self._loss_op 64 | 65 | 66 | class L1Norm( NNLoss ): 67 | """ 68 | L1 ノルムの損失関数 69 | NNLoss クラスの子クラスとして定義 70 | """ 71 | def __init__( self, node_name = "Loss_L1Norm_op" ): 72 | self._loss_op = None 73 | self._node_name = node_name 74 | 75 | return 76 | 77 | def loss( self, t_holder, y_out_op, node_name = "Loss_L1Norm_op" ): 78 | # tf.reduce_mean(...) でバッチサイズに対しての平均をとる。 79 | self._loss_op = tf.reduce_mean( 80 | tf.abs( t_holder - y_out_op ) 81 | ) 82 | 83 | return self._loss_op 84 | 85 | 86 | class L2Norm( NNLoss ): 87 | """ 88 | L2 ノルムの損失関数 89 | NNLoss クラスの子クラスとして定義 90 | """ 91 | def __init__( self, node_name = "Loss_L2Norm_op" ): 92 | self._loss_op = None 93 | self._node_name = node_name 94 | 95 | return 96 | 97 | def loss( self, t_holder, y_out_op, node_name = "Loss_L2Norm_op" ): 98 | self._loss_op = tf.reduce_mean( 99 | tf.square( t_holder - y_out_op ) 100 | ) 101 | 102 | return self._loss_op 103 | 104 | 105 | class BinaryCrossEntropy( NNLoss ): 106 | """ 107 | 2値のクロス・エントロピーの損失関数 108 | NNLoss クラスの子クラスとして定義 109 | """ 110 | def __init__( self, node_name = "Loss_BinaryCrossEntropy_op" ): 111 | self._loss_op = None 112 | self._node_name = node_name 113 | 114 | return 115 | 116 | def loss( self, t_holder, y_out_op ): 117 | self._loss_op = -tf.reduce_sum( 118 | t_holder * tf.log( y_out_op ) + ( 1 - t_holder ) * tf.log( 1 - y_out_op ) 119 | ) 120 | 121 | return self._loss_op 122 | 123 | 124 | class CrossEntropy( NNLoss ): 125 | """ 126 | クロス・エントロピーの損失関数 127 | NNLoss クラスの子クラスとして定義 128 | """ 129 | def __init__( self, node_name = "Loss_CrossEntropy_op" ): 130 | self._loss_op = None 131 | self._node_name = node_name 132 | 133 | return 134 | 135 | def loss( self, t_holder, y_out_op, node_name = "Loss_CrossEntropy_op" ): 136 | # softmax で正規化済みの場合 137 | # tf.clip_by_value(...) : 下限値、上限値を設定し, 値が更新されないことを防止 138 | self._loss_op = tf.reduce_mean( # ミニバッチ度に平均値を計算 139 | -tf.reduce_sum( 140 | t_holder * tf.log( tf.clip_by_value(y_out_op, 1e-10, 1.0) ), 141 | reduction_indices = [1] # sum をとる行列の方向 ( 1:row 方向 ) 142 | ) 143 | ) 144 | 145 | return self._loss_op 146 | 147 | 148 | class SoftmaxCrossEntropy( NNLoss ): 149 | """ 150 | ソフトマックス・クロス・エントロピーの損失関数 151 | NNLoss クラスの子クラスとして定義 152 | """ 153 | def __init__( self, node_name = "Loss_SoftmaxCrossEntropy_op" ): 154 | self._loss_op = None 155 | self._node_name = node_name 156 | 157 | return 158 | 159 | def loss( self, t_holder, y_out_op ): 160 | # softmax で正規化済みでない場合 161 | self._loss_op = tf.reduce_mean( 162 | tf.nn.softmax_cross_entropy_with_logits( 163 | labels = t_holder, 164 | logits = y_out_op 165 | ) 166 | ) 167 | 168 | return self._loss_op 169 | 170 | 171 | class SparseSoftmaxCrossEntropy( NNLoss ): 172 | """ 173 | 疎なソフトマックス・クロス・エントロピーの損失関数 174 | NNLoss クラスの子クラスとして定義 175 | """ 176 | def __init__( self, node_name = "Loss_SparseSoftmaxCrossEntropy_op" ): 177 | self._loss_op = None 178 | self._node_name = node_name 179 | 180 | return 181 | 182 | def loss( self, t_holder, y_out_op ): 183 | self._loss_op = tf.reduce_mean( 184 | tf.nn.sparse_softmax_cross_entropy_with_logits( 185 | labels = t_holder, 186 | logits = y_out_op 187 | ) 188 | ) 189 | 190 | return self._loss_op 191 | 192 | 193 | -------------------------------------------------------------------------------- /CNN_TensorFlow/NNActivation.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/21] : 新規作成 7 | [17/11/18] : NNActivation クラスの仕様変更。NNActivation クラスの子クラス定義 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNActivation( object ): 19 | """ 20 | ニューラルネットワークの活性化関数を表すクラス 21 | 実際の活性化関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _activate_op : 活性化関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, input = None, node_name = "Activation_op" ): 34 | self._activate_op = input 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNActivation" ) 41 | print( self ) 42 | print( str ) 43 | print( "_activate_op :", self._activate_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | def activate( self, input, node_name = "Activation_op" ): 49 | """ 50 | 活性化関数のオペレーターを返す。 51 | 52 | [Input] 53 | input : Operator or placeholder 54 | 活性化関数の入力となる Operatore、又は placeholder 55 | 56 | [Output] 57 | 活性化関数のオペレーター 58 | """ 59 | return self._activate_op 60 | 61 | 62 | class Sigmoid( NNActivation ): 63 | """ 64 | シグモイド関数の活性化関数 65 | NNActivation クラスの子クラスとして定義 66 | """ 67 | def __init__( self, input = None, node_name = "Activate_Sigmoid_op" ): 68 | self._activate_op = tf.nn.sigmoid( input, name = node_name ) 69 | self._node_name = node_name 70 | 71 | return 72 | 73 | def activate( self, input, node_name = "Activate_Sigmoid_op" ): 74 | self._activate_op = tf.nn.sigmoid( input, name = node_name ) 75 | self._node_name = node_name 76 | 77 | return self._activate_op 78 | 79 | 80 | class Relu( NNActivation ): 81 | """ 82 | Relu 関数の活性化関数 83 | NNActivation クラスの子クラスとして定義 84 | """ 85 | def __init__( self, input, node_name = "Activate_Relu_op" ): 86 | self._activate_op = tf.nn.relu( input, name = node_name ) 87 | self._node_name = node_name 88 | 89 | return 90 | 91 | def activate( self, input, node_name = "Activate_Relu_op" ): 92 | self._activate_op = tf.nn.relu( input, name = node_name ) 93 | self._node_name = node_name 94 | 95 | return self._activate_op 96 | 97 | 98 | class Softmax( NNActivation ): 99 | """ 100 | softmax 関数の活性化関数 101 | NNActivation クラスの子クラスとして定義 102 | """ 103 | def __init__( self, input = None, node_name = "Activate_Softmax_op" ): 104 | self._activate_op = tf.nn.softmax( input, name = node_name ) 105 | self._node_name = node_name 106 | 107 | return 108 | 109 | def activate( self, input, node_name = "Activate_Softmax_op" ): 110 | self._activate_op = tf.nn.softmax( input, name = node_name ) 111 | self._node_name = node_name 112 | 113 | return self._activate_op 114 | 115 | -------------------------------------------------------------------------------- /CNN_TensorFlow/NNLoss.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/xx/xx] : 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | class NNLoss( object ): 18 | """ 19 | ニューラルネットワークの損失関数(評価関数、誤差関数)を表すクラス 20 | 実際の損失関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 21 | ------------------------------------------------------------------------------------------------ 22 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 23 | _loss_op : 損失関数の Operater 24 | _node_name : str 25 | この Operator ノードの名前 26 | 27 | [protedted] protedted な使用法を想定 28 | 29 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 30 | 31 | """ 32 | def __init__( self, node_name = "Loss_op" ): 33 | self._loss_op = loss( t_holder, y_out_op, node_name ) 34 | self._node_name = node_name 35 | 36 | return 37 | 38 | def print( str ): 39 | print( "NNLoss" ) 40 | print( self ) 41 | print( str ) 42 | print( "_loss_op :", self._loss_op ) 43 | print( "_node_name :", self._node_name ) 44 | 45 | return 46 | 47 | 48 | def loss( self, t_holder, y_out_op ): 49 | """ 50 | 損失関数のオペレーターを返す。 51 | 52 | [Input] 53 | _t_holder : Placeholder 54 | 教師データの Placeholder 55 | _y_out_op : Operator 56 | 出力の Operator 57 | 58 | [Output] 59 | 損失関数のオペレーター 60 | """ 61 | self._loss_op = None 62 | 63 | return self._loss_op 64 | 65 | 66 | class L1Norm( NNLoss ): 67 | """ 68 | L1 ノルムの損失関数 69 | NNLoss クラスの子クラスとして定義 70 | """ 71 | def __init__( self, node_name = "Loss_L1Norm_op" ): 72 | self._loss_op = None 73 | self._node_name = node_name 74 | 75 | return 76 | 77 | def loss( self, t_holder, y_out_op, node_name = "Loss_L1Norm_op" ): 78 | # tf.reduce_mean(...) でバッチサイズに対しての平均をとる。 79 | self._loss_op = tf.reduce_mean( 80 | tf.abs( t_holder - y_out_op ) 81 | ) 82 | 83 | return self._loss_op 84 | 85 | 86 | class L2Norm( NNLoss ): 87 | """ 88 | L2 ノルムの損失関数 89 | NNLoss クラスの子クラスとして定義 90 | """ 91 | def __init__( self, node_name = "Loss_L2Norm_op" ): 92 | self._loss_op = None 93 | self._node_name = node_name 94 | 95 | return 96 | 97 | def loss( self, t_holder, y_out_op, node_name = "Loss_L2Norm_op" ): 98 | self._loss_op = tf.reduce_mean( 99 | tf.square( t_holder - y_out_op ) 100 | ) 101 | 102 | return self._loss_op 103 | 104 | 105 | class BinaryCrossEntropy( NNLoss ): 106 | """ 107 | 2値のクロス・エントロピーの損失関数 108 | NNLoss クラスの子クラスとして定義 109 | """ 110 | def __init__( self, node_name = "Loss_BinaryCrossEntropy_op" ): 111 | self._loss_op = None 112 | self._node_name = node_name 113 | 114 | return 115 | 116 | def loss( self, t_holder, y_out_op ): 117 | self._loss_op = -tf.reduce_sum( 118 | t_holder * tf.log( y_out_op ) + ( 1 - t_holder ) * tf.log( 1 - y_out_op ) 119 | ) 120 | 121 | return self._loss_op 122 | 123 | 124 | class CrossEntropy( NNLoss ): 125 | """ 126 | クロス・エントロピーの損失関数 127 | NNLoss クラスの子クラスとして定義 128 | """ 129 | def __init__( self, node_name = "Loss_CrossEntropy_op" ): 130 | self._loss_op = None 131 | self._node_name = node_name 132 | 133 | return 134 | 135 | def loss( self, t_holder, y_out_op, node_name = "Loss_CrossEntropy_op" ): 136 | # softmax で正規化済みの場合 137 | # tf.clip_by_value(...) : 下限値、上限値を設定 138 | self._loss_op = tf.reduce_mean( # ミニバッチ度に平均値を計算 139 | -tf.reduce_sum( 140 | t_holder * tf.log( tf.clip_by_value(y_out_op, 1e-10, 1.0) ), 141 | reduction_indices = [1] # sum をとる行列の方向 ( 1:row 方向 ) 142 | ) 143 | ) 144 | 145 | return self._loss_op 146 | 147 | 148 | class SoftmaxCrossEntropy( NNLoss ): 149 | """ 150 | ソフトマックス・クロス・エントロピーの損失関数 151 | NNLoss クラスの子クラスとして定義 152 | """ 153 | def __init__( self, node_name = "Loss_SoftmaxCrossEntropy_op" ): 154 | self._loss_op = None 155 | self._node_name = node_name 156 | 157 | return 158 | 159 | def loss( self, t_holder, y_out_op ): 160 | # softmax で正規化済みでない場合 161 | self._loss_op = tf.reduce_mean( 162 | tf.nn.softmax_cross_entropy_with_logits( 163 | labels = t_holder, 164 | logits = y_out_op 165 | ) 166 | ) 167 | 168 | return self._loss_op 169 | 170 | 171 | class SparseSoftmaxCrossEntropy( NNLoss ): 172 | """ 173 | 疎なソフトマックス・クロス・エントロピーの損失関数 174 | NNLoss クラスの子クラスとして定義 175 | """ 176 | def __init__( self, node_name = "Loss_SparseSoftmaxCrossEntropy_op" ): 177 | self._loss_op = None 178 | self._node_name = node_name 179 | 180 | return 181 | 182 | def loss( self, t_holder, y_out_op ): 183 | self._loss_op = tf.reduce_mean( 184 | tf.nn.sparse_softmax_cross_entropy_with_logits( 185 | labels = t_holder, 186 | logits = y_out_op 187 | ) 188 | ) 189 | 190 | return self._loss_op 191 | 192 | 193 | -------------------------------------------------------------------------------- /CNN_TensorFlow/NNOptimizer.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/11/20] : 最急降下法で学習率が幾何学的に減衰していく最適化アルゴリズム GradentDecentDecay 追加 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNOptimzer( object ): 19 | """ 20 | ニューラルネットワークの最適化アルゴリズム Optimizer を表すクラス 21 | 実際の最適化アルゴリズムを表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _optimizer : Optimizer 25 | 最適化アルゴリズム 26 | _train_step : 27 | トレーニングステップ 28 | _node_name : str 29 | この Optimizer ノードの名前 30 | 31 | _learning_rate : float 32 | 学習率 (0.0~1.0) 33 | 34 | [protedted] protedted な使用法を想定 35 | 36 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 37 | 38 | """ 39 | def __init__( self, learning_rate = 0.001, node_name = "Optimizer" ): 40 | self._optimizer = None 41 | self._train_step = None 42 | self._node_name = node_name 43 | self._learning_rate = learning_rate 44 | 45 | return 46 | 47 | def print( str ): 48 | print( "NNOptimizer" ) 49 | print( self ) 50 | print( str ) 51 | print( "_optimizer :", self._optimizer ) 52 | print( "_train_step :", self._train_step ) 53 | print( "_node_name :", self._node_name ) 54 | print( "_learning_rate :", self._learning_rate ) 55 | 56 | return 57 | 58 | def optimizer( self ): 59 | """ 60 | 最適化アルゴリズム Optimizer の設定を行う。 61 | 62 | [Output] 63 | optimizer 64 | """ 65 | return self._optimizer 66 | 67 | 68 | def train_step( self, loss_op ): 69 | """ 70 | トレーニングステップの設定を行う。 71 | 72 | [Input] 73 | loss_op : Operation 74 | 損失関数のオペレーター 75 | 76 | [Output] 77 | optimizer のトレーニングステップ 78 | """ 79 | return self._train_step 80 | 81 | 82 | class GradientDecent( NNOptimzer ): 83 | """ 84 | 最急降下法を表すクラス 85 | NNOptimizer クラスの子クラスとして定義 86 | """ 87 | def __init__( self, learning_rate = 0.001, node_name = "GradientDecent_Optimizer" ): 88 | self._learning_rate = learning_rate 89 | self._node_name = node_name 90 | self._optimizer = self.optimizer() 91 | self._train_step = None 92 | 93 | return 94 | 95 | def optimizer( self ): 96 | self._optimizer = tf.train.GradientDescentOptimizer( learning_rate = self._learning_rate ) 97 | return self._optimizer 98 | 99 | def train_step( self, loss_op ): 100 | self._train_step = self._optimizer.minimize( loss_op ) 101 | return self._train_step 102 | 103 | 104 | class GradientDecentDecay( NNOptimzer ): 105 | """ 106 | 最急降下法(学習率が減衰)を表すクラス 107 | NNOptimizer クラスの子クラスとして定義 108 | 109 | 減衰 110 | learning_rate * ( 1 - learning_rate)^(n_generation/n_gen_to_wait) 111 | [public] 112 | _n_generation : int 113 | 学習率を幾何学的に減衰させるためのパラメータ 114 | _n_gen_to_wait : int 115 | 学習率を幾何学的に減衰させるためのパラメータ 116 | 学習率を減衰されるステップ間隔 117 | _lr_recay : float 118 | 学習率を幾何学的に減衰させるためのパラメータ 119 | 120 | _recay_learning_rate : 121 | tf.train.exponential_decay(...) の戻り値 122 | """ 123 | def __init__( 124 | self, learning_rate = 0.001, 125 | n_generation = 500, n_gen_to_wait = 5, 126 | lr_recay = 0.1, 127 | node_name = "GradientDecentDecay_Optimizer" 128 | ): 129 | self._learning_rate = learning_rate 130 | self._n_generation = n_generation 131 | self._n_gen_to_wait = n_gen_to_wait 132 | self._lr_recay = lr_recay 133 | 134 | self._recay_learning_rate = tf.train.exponential_decay( 135 | learning_rate = learning_rate, 136 | global_step = n_generation, 137 | decay_steps = n_gen_to_wait, 138 | decay_rate = lr_recay, 139 | staircase = True 140 | ) 141 | 142 | self._node_name = node_name 143 | self._optimizer = self.optimizer() 144 | self._train_step = None 145 | 146 | return 147 | 148 | def optimizer( self ): 149 | self._optimizer = tf.train.GradientDescentOptimizer( learning_rate = self._recay_learning_rate ) 150 | return self._optimizer 151 | 152 | def train_step( self, loss_op ): 153 | self._train_step = self._optimizer.minimize( loss_op ) 154 | return self._train_step 155 | 156 | 157 | class Momentum( NNOptimzer ): 158 | """ 159 | モメンタム アルゴリズムを表すクラス 160 | NNOptimizer クラスの子クラスとして定義 161 | """ 162 | def __init__( self, learning_rate = 0.001, momentum = 0.9, node_name = "Momentum_Optimizer" ): 163 | self._learning_rate = learning_rate 164 | self._momentum = momentum 165 | self._node_name = node_name 166 | self._optimizer = self.optimizer() 167 | self._train_step = None 168 | 169 | return 170 | 171 | def optimizer( self ): 172 | self._optimizer = tf.train.MomentumOptimizer( 173 | learning_rate = self._learning_rate, 174 | momentum = self._momentum, 175 | use_nesterov = False 176 | ) 177 | 178 | return self._optimizer 179 | 180 | def train_step( self, loss_op ): 181 | self._train_step = self._optimizer.minimize( loss_op ) 182 | return self._train_step 183 | 184 | 185 | class NesterovMomentum( NNOptimzer ): 186 | """ 187 | Nesterov モメンタム アルゴリズムを表すクラス 188 | NNOptimizer クラスの子クラスとして定義 189 | """ 190 | def __init__( self, learning_rate = 0.001, momentum = 0.9, node_name = "NesterovMomentum_Optimizer" ): 191 | self._learning_rate = learning_rate 192 | self._momentum = momentum 193 | self._node_name = node_name 194 | self._optimizer = self.optimizer() 195 | self._train_step = None 196 | 197 | return 198 | 199 | def optimizer( self ): 200 | self._optimizer = tf.train.MomentumOptimizer( 201 | learning_rate = self._learning_rate, 202 | momentum = self._momentum, 203 | use_nesterov = True 204 | ) 205 | 206 | return self._optimizer 207 | 208 | def train_step( self, loss_op ): 209 | self._train_step = self._optimizer.minimize( loss_op ) 210 | return self._train_step 211 | 212 | 213 | class Adagrad( NNOptimzer ): 214 | """ 215 | Adagrad アルゴリズムを表すクラス 216 | NNOptimizer クラスの子クラスとして定義 217 | """ 218 | def __init__( self, learning_rate = 0.001, node_name = "Adagrad_Optimizer" ): 219 | self._learning_rate = learning_rate 220 | self._node_name = node_name 221 | self._optimizer = self.optimizer() 222 | self._train_step = None 223 | 224 | return 225 | 226 | def optimizer( self ): 227 | self._optimizer = tf.train.AdagradOptimizer( learning_rate = self._learning_rate ) 228 | return self._optimizer 229 | 230 | def train_step( self, loss_op ): 231 | self._train_step = self._optimizer.minimize( loss_op ) 232 | return self._train_step 233 | 234 | 235 | class Adadelta( NNOptimzer ): 236 | """ 237 | Adadelta アルゴリズムを表すクラス 238 | NNOptimizer クラスの子クラスとして定義 239 | """ 240 | def __init__( self, learning_rate = 0.001, rho = 0.95, node_name = "Adadelta_Optimizer" ): 241 | self._learning_rate = learning_rate 242 | self._rho = rho 243 | self._node_name = node_name 244 | self._optimizer = self.optimizer() 245 | self._train_step = None 246 | 247 | return 248 | 249 | def optimizer( self ): 250 | self._optimizer = tf.train.AdadeltaOptimizer( learning_rate = self._learning_rate, rho = self._rho ) 251 | return self._optimizer 252 | 253 | def train_step( self, loss_op ): 254 | self._train_step = self._optimizer.minimize( loss_op ) 255 | return self._train_step 256 | 257 | -------------------------------------------------------------------------------- /CNN_TensorFlow/NeuralNetworkBase.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/14] : 新規作成 7 | [17/11/19] : scikit-learn ライブラリの推定器 estimator の基本クラス `BaseEstimator`, `ClassifierMixin` を継承しているように変更 8 | : 各種抽象メソッド追加 9 | [17/12/01] : TensorBoard に計算グラフを表示するためのファイルを書き込むための関数 write_tensorboard_graph(...) 追加 10 | [xx/xx/xx] : 11 | 12 | """ 13 | 14 | from abc import ABCMeta, abstractmethod # 抽象クラスを作成するための ABC クラス 15 | 16 | import numpy 17 | 18 | # scikit-learn ライブラリ関連 19 | from sklearn.base import BaseEstimator # 推定器 Estimator の上位クラス. get_params(), set_params() 関数が定義されている. 20 | from sklearn.base import ClassifierMixin # 推定器 Estimator の上位クラス. score() 関数が定義されている. 21 | 22 | # TensorFlow ライブラリ 23 | import tensorflow as tf 24 | from tensorflow.python.framework import ops 25 | 26 | import NNActivation 27 | from NNActivation import NNActivation # ニューラルネットワークの活性化関数を表すクラス 28 | from NNActivation import Sigmoid 29 | from NNActivation import Relu 30 | from NNActivation import Softmax 31 | 32 | import NNLoss # ニューラルネットワークの損失関数を表すクラス 33 | from NNLoss import L1Norm 34 | from NNLoss import L2Norm 35 | from NNLoss import BinaryCrossEntropy 36 | from NNLoss import CrossEntropy 37 | from NNLoss import SoftmaxCrossEntropy 38 | from NNLoss import SparseSoftmaxCrossEntropy 39 | 40 | import NNOptimizer # ニューラルネットワークの最適化アルゴリズム Optimizer を表すクラス 41 | from NNOptimizer import GradientDecent 42 | from NNOptimizer import Momentum 43 | from NNOptimizer import NesterovMomentum 44 | from NNOptimizer import Adagrad 45 | from NNOptimizer import Adadelta 46 | 47 | 48 | class NeuralNetworkBase( BaseEstimator, ClassifierMixin ): 49 | """ 50 | ニューラルネットワークの基底クラス(自作クラス) 51 | scikit-learn ライブラリの推定器 estimator の基本クラス BaseEstimator, ClassifierMixin を継承している. 52 | TensorFlow ライブラリを使用 53 | ニューラルネットワークの基本的なフレームワークを想定した仮想メソッドからなる抽象クラス。 54 | 実際のニューラルネットワークを表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 55 | 56 | ---------------------------------------------------------------------------------------------------- 57 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 58 | _session : tf.Session() 59 | 自身の Session 60 | _init_var_op : tf.global_variables_initializer() 61 | 全 Variable の初期化オペレーター 62 | 63 | _loss_op : Operator 64 | 損失関数を表すオペレーター 65 | _optimizer : Optimizer 66 | モデルの最適化アルゴリズム 67 | _train_step : 68 | トレーニングステップ 69 | _y_out_op : Operator 70 | モデルの出力のオペレーター 71 | 72 | [protedted] protedted な使用法を想定 73 | 74 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 75 | 76 | """ 77 | 78 | def __init__( self, session = tf.Session() ): 79 | """ 80 | コンストラクタ(厳密にはイニシャライザ) 81 | """ 82 | # メンバ変数の初期化 83 | self._session = session 84 | self._init_var_op = None 85 | 86 | self._loss_op = None 87 | self._optimizer = None 88 | self._train_step = None 89 | self._y_out_op = None 90 | 91 | return 92 | 93 | 94 | def print( self, str ): 95 | print( "NeuralNetworkBase" ) 96 | print( self ) 97 | print( str ) 98 | 99 | print( "_session : \n", self._session ) 100 | print( "_init_var_op : \n", self._init_var_op ) 101 | print( "_loss_op : \n", self._loss_op ) 102 | print( "_y_out_op : \n", self._y_out_op ) 103 | 104 | return 105 | 106 | 107 | @abstractmethod 108 | def model( self ): 109 | """ 110 | モデルの定義を行い、 111 | 最終的なモデルの出力のオペレーター self._y_out_op を設定する。 112 | (抽象メソッド) 113 | 114 | [Output] 115 | self._y_out_op : Operator 116 | モデルの出力のオペレーター 117 | """ 118 | return self._y_out_op 119 | 120 | 121 | @abstractmethod 122 | def loss( self, nnLoss ): 123 | """ 124 | 損失関数(誤差関数、コスト関数)の定義を行う。 125 | (抽象メソッド) 126 | 127 | [Input] 128 | nnLoss : NNLoss クラスのオブジェクト 129 | 130 | [Output] 131 | self._loss_op : Operator 132 | 損失関数を表すオペレーター 133 | """ 134 | return self._loss_op 135 | 136 | 137 | @abstractmethod 138 | def optimizer( self, nnOptimizer ): 139 | """ 140 | モデルの最適化アルゴリズムの設定を行う。(抽象メソッド) 141 | 142 | [Input] 143 | nnOptimizer : NNOptimizer のクラスのオブジェクト 144 | 145 | [Output] 146 | optimizer の train_step 147 | 148 | """ 149 | return self._train_step 150 | 151 | 152 | @abstractmethod 153 | def fit( self, X_train, y_train ): 154 | """ 155 | 指定されたトレーニングデータで、モデルの fitting 処理を行う。(抽象メソッド) 156 | 157 | [Input] 158 | X_train : numpy.ndarray ( shape = [n_samples, n_features] ) 159 | トレーニングデータ(特徴行列) 160 | 161 | y_train : numpy.ndarray ( shape = [n_samples] ) 162 | レーニングデータ用のクラスラベル(教師データ)のリスト 163 | 164 | [Output] 165 | self : 自身のオブジェクト 166 | """ 167 | return self 168 | 169 | 170 | @abstractmethod 171 | def predict( self, X_features ): 172 | """ 173 | fitting 処理したモデルで、推定を行い、予想値を返す。(抽象メソッド) 174 | 175 | [Input] 176 | X_features : numpy.ndarry ( shape = [n_samples, n_features] ) 177 | 予想したい特徴行列 178 | 179 | [Output] 180 | results : numpy.ndaary ( shape = [n_samples] ) 181 | 予想結果(分類モデルの場合は、クラスラベル) 182 | """ 183 | return 184 | 185 | 186 | @abstractmethod 187 | def predict_proba( self, X_test ): 188 | """ 189 | fitting 処理したモデルで、推定を行い、クラスの所属確率の予想値を返す。(抽象メソッド) 190 | proba : probability 191 | 192 | [Input] 193 | X_test : numpy.ndarry ( shape = [n_samples, n_features] ) 194 | 予想したい特徴行列 195 | """ 196 | return 197 | 198 | @abstractmethod 199 | def accuracy( self, X_test, y_test ): 200 | """ 201 | 指定したデータでの正解率 [accuracy] を計算する。 202 | """ 203 | return 204 | 205 | @abstractmethod 206 | def accuracy_labels( self, X_test, y_test ): 207 | """ 208 | 指定したデータでのラベル毎の正解率 [acuuracy] を算出する。 209 | """ 210 | return 211 | 212 | 213 | def write_tensorboard_graph( self, dir = "./TensorBoard" ): 214 | """ 215 | TensorBoard に計算グラフを表示するためのファイルを書き込む。 216 | [Input] 217 | dir : str 218 | TensorBoard 用のファイルを作成するディレクトリのパス 219 | """ 220 | # TensorBoard 用のファイル(フォルダ)を作成 221 | merged = tf.summary.merge_all() # Add summaries to tensorboard 222 | summary_writer = tf.summary.FileWriter( dir, graph = self._session.graph ) # tensorboard --logdir=${PWD} 223 | 224 | return -------------------------------------------------------------------------------- /GAN_DCGAN_TensorFlow/NNActivation.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/21] : 新規作成 7 | [17/11/18] : NNActivation クラスの仕様変更。NNActivation クラスの子クラス定義 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNActivation( object ): 19 | """ 20 | ニューラルネットワークの活性化関数を表すクラス 21 | 実際の活性化関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _activate_op : 活性化関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Activation_op" ): 34 | self._activate_op = None 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNActivation" ) 41 | print( self ) 42 | print( str ) 43 | print( "_activate_op :", self._activate_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | def activate( self, input, node_name = "Activation_op" ): 49 | """ 50 | 活性化関数のオペレーターを返す。 51 | 52 | [Input] 53 | input : Operator or placeholder 54 | 活性化関数の入力となる Operatore、又は placeholder 55 | 56 | [Output] 57 | 活性化関数のオペレーター 58 | """ 59 | return self._activate_op 60 | 61 | 62 | class Sigmoid( NNActivation ): 63 | """ 64 | シグモイド関数の活性化関数 65 | NNActivation クラスの子クラスとして定義 66 | """ 67 | def __init__( self, node_name = "Activate_Sigmoid_op" ): 68 | self._activate_op = None 69 | self._node_name = node_name 70 | 71 | return 72 | 73 | def activate( self, input, node_name = "Activate_Sigmoid_op" ): 74 | self._activate_op = tf.nn.sigmoid( input, name = node_name ) 75 | self._node_name = node_name 76 | 77 | return self._activate_op 78 | 79 | 80 | class Relu( NNActivation ): 81 | """ 82 | Relu 関数の活性化関数 83 | NNActivation クラスの子クラスとして定義 84 | """ 85 | def __init__( self, node_name = "Activate_Relu_op" ): 86 | self._activate_op = None 87 | self._node_name = node_name 88 | 89 | return 90 | 91 | def activate( self, input, node_name = "Activate_Relu_op" ): 92 | self._activate_op = tf.nn.relu( input, name = node_name ) 93 | self._node_name = node_name 94 | 95 | return self._activate_op 96 | 97 | 98 | class Softmax( NNActivation ): 99 | """ 100 | softmax 関数の活性化関数 101 | NNActivation クラスの子クラスとして定義 102 | """ 103 | def __init__( self, node_name = "Activate_Softmax_op" ): 104 | self._activate_op = None 105 | self._node_name = node_name 106 | 107 | return 108 | 109 | def activate( self, input, node_name = "Activate_Softmax_op" ): 110 | self._activate_op = tf.nn.softmax( input, name = node_name ) 111 | self._node_name = node_name 112 | 113 | return self._activate_op 114 | 115 | -------------------------------------------------------------------------------- /GAN_DCGAN_TensorFlow/NNLoss.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/12/04] : 損失関数の処理の名前空間を設定するように修正 8 | [17/xx/xx] : 9 | : 10 | """ 11 | 12 | import numpy 13 | 14 | # TensorFlow ライブラリ 15 | import tensorflow as tf 16 | from tensorflow.python.framework import ops 17 | 18 | class NNLoss( object ): 19 | """ 20 | ニューラルネットワークの損失関数(評価関数、誤差関数)を表すクラス 21 | 実際の損失関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _loss_op : 損失関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Loss_op" ): 34 | self._loss_op = loss( t_holder, y_out_op, node_name ) 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNLoss" ) 41 | print( self ) 42 | print( str ) 43 | print( "_loss_op :", self._loss_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | 49 | def loss( self, t_holder, y_out_op ): 50 | """ 51 | 損失関数のオペレーターを返す。 52 | 53 | [Input] 54 | _t_holder : Placeholder 55 | 教師データの Placeholder 56 | _y_out_op : Operator 57 | 出力の Operator 58 | 59 | [Output] 60 | 損失関数のオペレーター 61 | """ 62 | # 名前空間の範囲 63 | with tf.name_scope( self._node_name ): 64 | self._loss_op = None 65 | 66 | return self._loss_op 67 | 68 | 69 | class L1Norm( NNLoss ): 70 | """ 71 | L1 ノルムの損失関数 72 | NNLoss クラスの子クラスとして定義 73 | """ 74 | def __init__( self, node_name = "Loss_L1Norm_op" ): 75 | self._loss_op = None 76 | self._node_name = node_name 77 | 78 | return 79 | 80 | def loss( self, t_holder, y_out_op, node_name = "Loss_L1Norm_op" ): 81 | with tf.name_scope( self._node_name ): 82 | # tf.reduce_mean(...) でバッチサイズに対しての平均をとる。 83 | self._loss_op = tf.reduce_mean( 84 | tf.abs( t_holder - y_out_op ) 85 | ) 86 | 87 | return self._loss_op 88 | 89 | 90 | class L2Norm( NNLoss ): 91 | """ 92 | L2 ノルムの損失関数 93 | NNLoss クラスの子クラスとして定義 94 | """ 95 | def __init__( self, node_name = "Loss_L2Norm_op" ): 96 | self._loss_op = None 97 | self._node_name = node_name 98 | 99 | return 100 | 101 | def loss( self, t_holder, y_out_op, node_name = "Loss_L2Norm_op" ): 102 | with tf.name_scope( self._node_name ): 103 | self._loss_op = tf.reduce_mean( 104 | tf.square( t_holder - y_out_op ) 105 | ) 106 | 107 | return self._loss_op 108 | 109 | 110 | class BinaryCrossEntropy( NNLoss ): 111 | """ 112 | 2値のクロス・エントロピーの損失関数 113 | NNLoss クラスの子クラスとして定義 114 | """ 115 | def __init__( self, node_name = "Loss_BinaryCrossEntropy_op" ): 116 | self._loss_op = None 117 | self._node_name = node_name 118 | 119 | return 120 | 121 | def loss( self, t_holder, y_out_op ): 122 | with tf.name_scope( self._node_name ): 123 | self._loss_op = -tf.reduce_sum( 124 | t_holder * tf.log( y_out_op ) + ( 1 - t_holder ) * tf.log( 1 - y_out_op ) 125 | ) 126 | 127 | return self._loss_op 128 | 129 | 130 | class CrossEntropy( NNLoss ): 131 | """ 132 | クロス・エントロピーの損失関数 133 | NNLoss クラスの子クラスとして定義 134 | """ 135 | def __init__( self, node_name = "Loss_CrossEntropy_op" ): 136 | self._loss_op = None 137 | self._node_name = node_name 138 | 139 | return 140 | 141 | def loss( self, t_holder, y_out_op, node_name = "Loss_CrossEntropy_op" ): 142 | with tf.name_scope( self._node_name ): 143 | # softmax で正規化済みの場合 144 | # tf.clip_by_value(...) : 下限値、上限値を設定し, 値が更新されないことを防止 145 | self._loss_op = tf.reduce_mean( # ミニバッチ度に平均値を計算 146 | -tf.reduce_sum( 147 | t_holder * tf.log( tf.clip_by_value(y_out_op, 1e-10, 1.0) ), 148 | reduction_indices = [1] # sum をとる行列の方向 ( 1:row 方向 ) 149 | ) 150 | ) 151 | 152 | return self._loss_op 153 | 154 | 155 | class SoftmaxCrossEntropy( NNLoss ): 156 | """ 157 | ソフトマックス・クロス・エントロピーの損失関数 158 | NNLoss クラスの子クラスとして定義 159 | """ 160 | def __init__( self, node_name = "Loss_SoftmaxCrossEntropy_op" ): 161 | self._loss_op = None 162 | self._node_name = node_name 163 | 164 | return 165 | 166 | def loss( self, t_holder, y_out_op ): 167 | with tf.name_scope( self._node_name ): 168 | # softmax で正規化済みでない場合 169 | self._loss_op = tf.reduce_mean( 170 | tf.nn.softmax_cross_entropy_with_logits( 171 | labels = t_holder, 172 | logits = y_out_op 173 | ) 174 | ) 175 | 176 | return self._loss_op 177 | 178 | 179 | class SparseSoftmaxCrossEntropy( NNLoss ): 180 | """ 181 | 疎なソフトマックス・クロス・エントロピーの損失関数 182 | NNLoss クラスの子クラスとして定義 183 | """ 184 | def __init__( self, node_name = "Loss_SparseSoftmaxCrossEntropy_op" ): 185 | self._loss_op = None 186 | self._node_name = node_name 187 | 188 | return 189 | 190 | def loss( self, t_holder, y_out_op ): 191 | with tf.name_scope( self._node_name ): 192 | self._loss_op = tf.reduce_mean( 193 | tf.nn.sparse_softmax_cross_entropy_with_logits( 194 | labels = t_holder, 195 | logits = y_out_op 196 | ) 197 | ) 198 | 199 | return self._loss_op 200 | 201 | 202 | -------------------------------------------------------------------------------- /MultilayerPerceptron_TensorFlow/NNActivation.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/21] : 新規作成 7 | [17/11/18] : NNActivation クラスの仕様変更。NNActivation クラスの子クラス定義 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNActivation( object ): 19 | """ 20 | ニューラルネットワークの活性化関数を表すクラス 21 | 実際の活性化関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _activate_op : 活性化関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Activation_op" ): 34 | self._activate_op = None 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNActivation" ) 41 | print( self ) 42 | print( str ) 43 | print( "_activate_op :", self._activate_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | def activate( self, input, node_name = "Activation_op" ): 49 | """ 50 | 活性化関数のオペレーターを返す。 51 | 52 | [Input] 53 | input : Operator or placeholder 54 | 活性化関数の入力となる Operatore、又は placeholder 55 | 56 | [Output] 57 | 活性化関数のオペレーター 58 | """ 59 | return self._activate_op 60 | 61 | 62 | class Sigmoid( NNActivation ): 63 | """ 64 | シグモイド関数の活性化関数 65 | NNActivation クラスの子クラスとして定義 66 | """ 67 | def __init__( self, node_name = "Activate_Sigmoid_op" ): 68 | self._activate_op = None 69 | self._node_name = node_name 70 | 71 | return 72 | 73 | def activate( self, input, node_name = "Activate_Sigmoid_op" ): 74 | self._activate_op = tf.nn.sigmoid( input, name = node_name ) 75 | self._node_name = node_name 76 | 77 | return self._activate_op 78 | 79 | 80 | class Relu( NNActivation ): 81 | """ 82 | Relu 関数の活性化関数 83 | NNActivation クラスの子クラスとして定義 84 | """ 85 | def __init__( self, node_name = "Activate_Relu_op" ): 86 | self._activate_op = None 87 | self._node_name = node_name 88 | 89 | return 90 | 91 | def activate( self, input, node_name = "Activate_Relu_op" ): 92 | self._activate_op = tf.nn.relu( input, name = node_name ) 93 | self._node_name = node_name 94 | 95 | return self._activate_op 96 | 97 | 98 | class Softmax( NNActivation ): 99 | """ 100 | softmax 関数の活性化関数 101 | NNActivation クラスの子クラスとして定義 102 | """ 103 | def __init__( self, node_name = "Activate_Softmax_op" ): 104 | self._activate_op = None 105 | self._node_name = node_name 106 | 107 | return 108 | 109 | def activate( self, input, node_name = "Activate_Softmax_op" ): 110 | self._activate_op = tf.nn.softmax( input, name = node_name ) 111 | self._node_name = node_name 112 | 113 | return self._activate_op 114 | 115 | -------------------------------------------------------------------------------- /MultilayerPerceptron_TensorFlow/NNLoss.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/xx/xx] : 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | class NNLoss( object ): 18 | """ 19 | ニューラルネットワークの損失関数(評価関数、誤差関数)を表すクラス 20 | 実際の損失関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 21 | ------------------------------------------------------------------------------------------------ 22 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 23 | _loss_op : 損失関数の Operater 24 | _node_name : str 25 | この Operator ノードの名前 26 | 27 | [protedted] protedted な使用法を想定 28 | 29 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 30 | 31 | """ 32 | def __init__( self, node_name = "Loss_op" ): 33 | self._loss_op = loss( t_holder, y_out_op, node_name ) 34 | self._node_name = node_name 35 | 36 | return 37 | 38 | def print( str ): 39 | print( "NNLoss" ) 40 | print( self ) 41 | print( str ) 42 | print( "_loss_op :", self._loss_op ) 43 | print( "_node_name :", self._node_name ) 44 | 45 | return 46 | 47 | 48 | def loss( self, t_holder, y_out_op ): 49 | """ 50 | 損失関数のオペレーターを返す。 51 | 52 | [Input] 53 | _t_holder : Placeholder 54 | 教師データの Placeholder 55 | _y_out_op : Operator 56 | 出力の Operator 57 | 58 | [Output] 59 | 損失関数のオペレーター 60 | """ 61 | self._loss_op = None 62 | 63 | return self._loss_op 64 | 65 | 66 | class L1Norm( NNLoss ): 67 | """ 68 | L1 ノルムの損失関数 69 | NNLoss クラスの子クラスとして定義 70 | """ 71 | def __init__( self, node_name = "Loss_L1Norm_op" ): 72 | self._loss_op = None 73 | self._node_name = node_name 74 | 75 | return 76 | 77 | def loss( self, t_holder, y_out_op, node_name = "Loss_L1Norm_op" ): 78 | # tf.reduce_mean(...) : 79 | self._loss_op = tf.reduce_mean( 80 | tf.abs( t_holder - y_out_op ) 81 | ) 82 | 83 | return self._loss_op 84 | 85 | 86 | class L2Norm( NNLoss ): 87 | """ 88 | L2 ノルムの損失関数 89 | NNLoss クラスの子クラスとして定義 90 | """ 91 | def __init__( self, node_name = "Loss_L2Norm_op" ): 92 | self._loss_op = None 93 | self._node_name = node_name 94 | 95 | return 96 | 97 | def loss( self, t_holder, y_out_op, node_name = "Loss_L2Norm_op" ): 98 | self._loss_op = tf.reduce_mean( 99 | tf.square( t_holder - y_out_op ) 100 | ) 101 | 102 | return self._loss_op 103 | 104 | 105 | class BinaryCrossEntropy( NNLoss ): 106 | """ 107 | 2値のクロス・エントロピーの損失関数 108 | NNLoss クラスの子クラスとして定義 109 | """ 110 | def __init__( self, node_name = "Loss_BinaryCrossEntropy_op" ): 111 | self._loss_op = None 112 | self._node_name = node_name 113 | 114 | return 115 | 116 | def loss( self, t_holder, y_out_op ): 117 | self._loss_op = -tf.reduce_sum( 118 | t_holder * tf.log( y_out_op ) + 119 | ( 1 - t_holder ) * tf.log( 1 - y_out_op ) 120 | ) 121 | 122 | return self._loss_op 123 | 124 | 125 | class CrossEntropy( NNLoss ): 126 | """ 127 | クロス・エントロピーの損失関数 128 | NNLoss クラスの子クラスとして定義 129 | """ 130 | def __init__( self, node_name = "Loss_CrossEntropy_op" ): 131 | self._loss_op = None 132 | self._node_name = node_name 133 | 134 | return 135 | 136 | def loss( self, t_holder, y_out_op, node_name = "Loss_CrossEntropy_op" ): 137 | # softmax で正規化済みの場合 138 | # tf.clip_by_value(...) : 下限値、上限値を設定 139 | self._loss_op = tf.reduce_mean( # ミニバッチ度に平均値を計算 140 | -tf.reduce_sum( 141 | t_holder * tf.log( tf.clip_by_value(y_out_op, 1e-10, 1.0) ), 142 | reduction_indices = [1] # sum をとる行列の方向 ( 1:row 方向 ) 143 | ) 144 | ) 145 | 146 | return self._loss_op 147 | 148 | 149 | class SoftmaxCrossEntropy( NNLoss ): 150 | """ 151 | ソフトマックス・クロス・エントロピーの損失関数 152 | NNLoss クラスの子クラスとして定義 153 | """ 154 | def __init__( self, node_name = "Loss_SoftmaxCrossEntropy_op" ): 155 | self._loss_op = None 156 | self._node_name = node_name 157 | 158 | return 159 | 160 | def loss( self, t_holder, y_out_op ): 161 | # softmax で正規化済みでない場合 162 | self._loss_op = tf.reduce_mean( 163 | tf.nn.softmax_cross_entropy_with_logits( 164 | labels = t_holder, 165 | logits = y_out_op 166 | ) 167 | ) 168 | 169 | return self._loss_op 170 | 171 | 172 | class SparseSoftmaxCrossEntropy( NNLoss ): 173 | """ 174 | 疎なソフトマックス・クロス・エントロピーの損失関数 175 | NNLoss クラスの子クラスとして定義 176 | """ 177 | def __init__( self, node_name = "Loss_SparseSoftmaxCrossEntropy_op" ): 178 | self._loss_op = None 179 | self._node_name = node_name 180 | 181 | return 182 | 183 | def loss( self, t_holder, y_out_op ): 184 | self._loss_op = tf.reduce_mean( 185 | tf.nn.sparse_softmax_cross_entropy_with_logits( 186 | logits = y_out_op, 187 | labels = t_holder 188 | ) 189 | ) 190 | 191 | return self._loss_op 192 | 193 | 194 | -------------------------------------------------------------------------------- /MultilayerPerceptron_TensorFlow/NNOptimizer.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/xx/xx] : 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNOptimzer( object ): 19 | """ 20 | ニューラルネットワークの最適化アルゴリズム Optimizer を表すクラス 21 | 実際の最適化アルゴリズムを表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _optimizer : Optimizer 25 | 最適化アルゴリズム 26 | _train_step : 27 | トレーニングステップ 28 | _node_name : str 29 | この Optimizer ノードの名前 30 | 31 | _learning_rate : float 32 | 学習率 (0.0~1.0) 33 | 34 | [protedted] protedted な使用法を想定 35 | 36 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 37 | 38 | """ 39 | def __init__( self, learning_rate = 0.001, node_name = "Optimizer" ): 40 | self._optimizer = None 41 | self._train_step = None 42 | self._node_name = node_name 43 | self._learning_rate = learning_rate 44 | 45 | return 46 | 47 | def print( str ): 48 | print( "NNOptimizer" ) 49 | print( self ) 50 | print( str ) 51 | print( "_optimizer :", self._optimizer ) 52 | print( "_train_step :", self._train_step ) 53 | print( "_node_name :", self._node_name ) 54 | print( "_learning_rate :", self._learning_rate ) 55 | 56 | return 57 | 58 | def optimizer( self ): 59 | """ 60 | 最適化アルゴリズム Optimizer の設定を行う。 61 | 62 | [Output] 63 | optimizer 64 | """ 65 | return self._optimizer 66 | 67 | 68 | def train_step( self, loss_op ): 69 | """ 70 | トレーニングステップの設定を行う。 71 | 72 | [Input] 73 | loss_op : Operation 74 | 損失関数のオペレーター 75 | 76 | [Output] 77 | optimizer のトレーニングステップ 78 | """ 79 | return self._train_step 80 | 81 | 82 | class GradientDecent( NNOptimzer ): 83 | """ 84 | 最急降下法を表すクラス 85 | NNOptimizer クラスの子クラスとして定義 86 | """ 87 | def __init__( self, learning_rate = 0.001, node_name = "GradientDecent_Optimizer" ): 88 | self._learning_rate = learning_rate 89 | self._node_name = node_name 90 | self._optimizer = self.optimizer() 91 | self._train_step = None 92 | 93 | return 94 | 95 | def optimizer( self ): 96 | self._optimizer = tf.train.GradientDescentOptimizer( learning_rate = self._learning_rate ) 97 | return self._optimizer 98 | 99 | def train_step( self, loss_op ): 100 | self._train_step = self._optimizer.minimize( loss_op ) 101 | return self._train_step 102 | 103 | 104 | class Momentum( NNOptimzer ): 105 | """ 106 | モメンタム アルゴリズムを表すクラス 107 | NNOptimizer クラスの子クラスとして定義 108 | """ 109 | def __init__( self, learning_rate = 0.001, momentum = 0.9, node_name = "Momentum_Optimizer" ): 110 | self._learning_rate = learning_rate 111 | self._momentum = momentum 112 | self._node_name = node_name 113 | self._optimizer = self.optimizer() 114 | self._train_step = None 115 | 116 | return 117 | 118 | def optimizer( self ): 119 | self._optimizer = tf.train.MomentumOptimizer( 120 | learning_rate = self._learning_rate, 121 | momentum = self._momentum, 122 | use_nesterov = False 123 | ) 124 | 125 | return self._optimizer 126 | 127 | def train_step( self, loss_op ): 128 | self._train_step = self._optimizer.minimize( loss_op ) 129 | return self._train_step 130 | 131 | 132 | class NesterovMomentum( NNOptimzer ): 133 | """ 134 | Nesterov モメンタム アルゴリズムを表すクラス 135 | NNOptimizer クラスの子クラスとして定義 136 | """ 137 | def __init__( self, learning_rate = 0.001, momentum = 0.9, node_name = "NesterovMomentum_Optimizer" ): 138 | self._learning_rate = learning_rate 139 | self._momentum = momentum 140 | self._node_name = node_name 141 | self._optimizer = self.optimizer() 142 | self._train_step = None 143 | 144 | return 145 | 146 | def optimizer( self ): 147 | self._optimizer = tf.train.MomentumOptimizer( 148 | learning_rate = self._learning_rate, 149 | momentum = self._momentum, 150 | use_nesterov = True 151 | ) 152 | 153 | return self._optimizer 154 | 155 | def train_step( self, loss_op ): 156 | self._train_step = self._optimizer.minimize( loss_op ) 157 | return self._train_step 158 | 159 | 160 | class Adagrad( NNOptimzer ): 161 | """ 162 | Adagrad アルゴリズムを表すクラス 163 | NNOptimizer クラスの子クラスとして定義 164 | """ 165 | def __init__( self, learning_rate = 0.001, node_name = "Adagrad_Optimizer" ): 166 | self._learning_rate = learning_rate 167 | self._node_name = node_name 168 | self._optimizer = self.optimizer() 169 | self._train_step = None 170 | 171 | return 172 | 173 | def optimizer( self ): 174 | self._optimizer = tf.train.AdagradOptimizer( learning_rate = self._learning_rate ) 175 | return self._optimizer 176 | 177 | def train_step( self, loss_op ): 178 | self._train_step = self._optimizer.minimize( loss_op ) 179 | return self._train_step 180 | 181 | 182 | class Adadelta( NNOptimzer ): 183 | """ 184 | Adadelta アルゴリズムを表すクラス 185 | NNOptimizer クラスの子クラスとして定義 186 | """ 187 | def __init__( self, learning_rate = 0.001, rho = 0.95, node_name = "Adadelta_Optimizer" ): 188 | self._learning_rate = learning_rate 189 | self._rho = rho 190 | self._node_name = node_name 191 | self._optimizer = self.optimizer() 192 | self._train_step = None 193 | 194 | return 195 | 196 | def optimizer( self ): 197 | self._optimizer = tf.train.AdadeltaOptimizer( learning_rate = self._learning_rate, rho = self._rho ) 198 | return self._optimizer 199 | 200 | def train_step( self, loss_op ): 201 | self._train_step = self._optimizer.minimize( loss_op ) 202 | return self._train_step 203 | 204 | -------------------------------------------------------------------------------- /MultilayerPerceptron_TensorFlow/NeuralNetworkBase.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/14] : 新規作成 7 | [17/11/19] : scikit-learn ライブラリの推定器 estimator の基本クラス `BaseEstimator`, `ClassifierMixin` を継承しているように変更 8 | : 各種抽象メソッド追加 9 | [17/12/01] : TensorBoard に計算グラフを表示するためのファイルを書き込むための関数 write_tensorboard_graph(...) 追加 10 | [xx/xx/xx] : 11 | 12 | """ 13 | 14 | from abc import ABCMeta, abstractmethod # 抽象クラスを作成するための ABC クラス 15 | 16 | import numpy 17 | 18 | # scikit-learn ライブラリ関連 19 | from sklearn.base import BaseEstimator # 推定器 Estimator の上位クラス. get_params(), set_params() 関数が定義されている. 20 | from sklearn.base import ClassifierMixin # 推定器 Estimator の上位クラス. score() 関数が定義されている. 21 | 22 | # TensorFlow ライブラリ 23 | import tensorflow as tf 24 | from tensorflow.python.framework import ops 25 | 26 | import NNActivation 27 | from NNActivation import NNActivation # ニューラルネットワークの活性化関数を表すクラス 28 | from NNActivation import Sigmoid 29 | from NNActivation import Relu 30 | from NNActivation import Softmax 31 | 32 | import NNLoss # ニューラルネットワークの損失関数を表すクラス 33 | from NNLoss import L1Norm 34 | from NNLoss import L2Norm 35 | from NNLoss import BinaryCrossEntropy 36 | from NNLoss import CrossEntropy 37 | from NNLoss import SoftmaxCrossEntropy 38 | from NNLoss import SparseSoftmaxCrossEntropy 39 | 40 | import NNOptimizer # ニューラルネットワークの最適化アルゴリズム Optimizer を表すクラス 41 | from NNOptimizer import GradientDecent 42 | from NNOptimizer import Momentum 43 | from NNOptimizer import NesterovMomentum 44 | from NNOptimizer import Adagrad 45 | from NNOptimizer import Adadelta 46 | 47 | 48 | class NeuralNetworkBase( BaseEstimator, ClassifierMixin ): 49 | """ 50 | ニューラルネットワークの基底クラス(自作クラス) 51 | scikit-learn ライブラリの推定器 estimator の基本クラス BaseEstimator, ClassifierMixin を継承している. 52 | TensorFlow ライブラリを使用 53 | ニューラルネットワークの基本的なフレームワークを想定した仮想メソッドからなる抽象クラス。 54 | 実際のニューラルネットワークを表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 55 | 56 | ---------------------------------------------------------------------------------------------------- 57 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 58 | _session : tf.Session() 59 | 自身の Session 60 | _init_var_op : tf.global_variables_initializer() 61 | 全 Variable の初期化オペレーター 62 | 63 | _loss_op : Operator 64 | 損失関数を表すオペレーター 65 | _optimizer : Optimizer 66 | モデルの最適化アルゴリズム 67 | _train_step : 68 | トレーニングステップ 69 | _y_out_op : Operator 70 | モデルの出力のオペレーター 71 | 72 | [protedted] protedted な使用法を想定 73 | 74 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 75 | 76 | """ 77 | 78 | def __init__( self, session = tf.Session() ): 79 | """ 80 | コンストラクタ(厳密にはイニシャライザ) 81 | """ 82 | # メンバ変数の初期化 83 | self._session = session 84 | self._init_var_op = None 85 | 86 | self._loss_op = None 87 | self._optimizer = None 88 | self._train_step = None 89 | self._y_out_op = None 90 | 91 | return 92 | 93 | 94 | def print( self, str ): 95 | print( "NeuralNetworkBase" ) 96 | print( self ) 97 | print( str ) 98 | 99 | print( "_session : \n", self._session ) 100 | print( "_init_var_op : \n", self._init_var_op ) 101 | print( "_loss_op : \n", self._loss_op ) 102 | print( "_y_out_op : \n", self._y_out_op ) 103 | 104 | return 105 | 106 | 107 | @abstractmethod 108 | def model( self ): 109 | """ 110 | モデルの定義を行い、 111 | 最終的なモデルの出力のオペレーター self._y_out_op を設定する。 112 | (抽象メソッド) 113 | 114 | [Output] 115 | self._y_out_op : Operator 116 | モデルの出力のオペレーター 117 | """ 118 | return self._y_out_op 119 | 120 | 121 | @abstractmethod 122 | def loss( self, nnLoss ): 123 | """ 124 | 損失関数(誤差関数、コスト関数)の定義を行う。 125 | (抽象メソッド) 126 | 127 | [Input] 128 | nnLoss : NNLoss クラスのオブジェクト 129 | 130 | [Output] 131 | self._loss_op : Operator 132 | 損失関数を表すオペレーター 133 | """ 134 | return self._loss_op 135 | 136 | 137 | @abstractmethod 138 | def optimizer( self, nnOptimizer ): 139 | """ 140 | モデルの最適化アルゴリズムの設定を行う。(抽象メソッド) 141 | 142 | [Input] 143 | nnOptimizer : NNOptimizer のクラスのオブジェクト 144 | 145 | [Output] 146 | optimizer の train_step 147 | 148 | """ 149 | return self._train_step 150 | 151 | 152 | @abstractmethod 153 | def fit( self, X_train, y_train ): 154 | """ 155 | 指定されたトレーニングデータで、モデルの fitting 処理を行う。(抽象メソッド) 156 | 157 | [Input] 158 | X_train : numpy.ndarray ( shape = [n_samples, n_features] ) 159 | トレーニングデータ(特徴行列) 160 | 161 | y_train : numpy.ndarray ( shape = [n_samples] ) 162 | レーニングデータ用のクラスラベル(教師データ)のリスト 163 | 164 | [Output] 165 | self : 自身のオブジェクト 166 | """ 167 | return self 168 | 169 | 170 | @abstractmethod 171 | def predict( self, X_features ): 172 | """ 173 | fitting 処理したモデルで、推定を行い、予想値を返す。(抽象メソッド) 174 | 175 | [Input] 176 | X_features : numpy.ndarry ( shape = [n_samples, n_features] ) 177 | 予想したい特徴行列 178 | 179 | [Output] 180 | results : numpy.ndaary ( shape = [n_samples] ) 181 | 予想結果(分類モデルの場合は、クラスラベル) 182 | """ 183 | return 184 | 185 | 186 | @abstractmethod 187 | def predict_proba( self, X_test ): 188 | """ 189 | fitting 処理したモデルで、推定を行い、クラスの所属確率の予想値を返す。(抽象メソッド) 190 | proba : probability 191 | 192 | [Input] 193 | X_test : numpy.ndarry ( shape = [n_samples, n_features] ) 194 | 予想したい特徴行列 195 | """ 196 | return 197 | 198 | @abstractmethod 199 | def accuracy( self, X_test, y_test ): 200 | """ 201 | 指定したデータでの正解率 [accuracy] を計算する。 202 | """ 203 | return 204 | 205 | @abstractmethod 206 | def accuracy_labels( self, X_test, y_test ): 207 | """ 208 | 指定したデータでのラベル毎の正解率 [acuuracy] を算出する。 209 | """ 210 | return 211 | 212 | 213 | def write_tensorboard_graph( self, dir = "./TensorBoard" ): 214 | """ 215 | TensorBoard に計算グラフを表示するためのファイルを書き込む。 216 | [Input] 217 | dir : str 218 | TensorBoard 用のファイルを作成するディレクトリのパス 219 | """ 220 | # TensorBoard 用のファイル(フォルダ)を作成 221 | merged = tf.summary.merge_all() # Add summaries to tensorboard 222 | summary_writer = tf.summary.FileWriter( dir, graph = self._session.graph ) # tensorboard --logdir=${PWD} 223 | 224 | return -------------------------------------------------------------------------------- /ObjectDetection_SSD_TensorFlow/VOC2007.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/ca59e212d07daef82cd96816922005fade10690c/ObjectDetection_SSD_TensorFlow/VOC2007.pkl -------------------------------------------------------------------------------- /ObjectDetection_SSD_TensorFlow/model/BoundingBox.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 5.0.1 環境 (TensorFlow 1.4.0 インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [18/05/14] : 新規作成 7 | [xx/xx/xx] : 8 | 9 | """ 10 | 11 | import numpy as np 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | # openCV ライブラリ 18 | import cv2 19 | 20 | 21 | class BoundingBox( object ): 22 | """ 23 | SSD [Single Shot muitibox Detector] で使用する、バウンディングボックスを表すクラス。 24 | Bouding Box is the result of comparison with default box. 25 | bouding box has loc (position) and class's label. 26 | 27 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 28 | _label : int 29 | バウンディングボックスの所属クラスのクラスラベル 30 | 31 | _rect_loc : list 32 | バウンディングボックスの長方形座標。 33 | [ center_x, center_y, width, height ] 34 | 35 | [protedted] protedted な使用法を想定 36 | 37 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 38 | 39 | """ 40 | def __init__( self, label, rect_loc ): 41 | self._label = label 42 | self._rect_loc = rect_loc 43 | 44 | return 45 | 46 | """ 47 | def __init__( self, label, center_x, center_y, height, width ): 48 | self._label = label 49 | self._rect_loc = [ center_x, center_y, height, width ] 50 | 51 | return 52 | """ 53 | 54 | def print( self, str = None ): 55 | print( "----------------------------------" ) 56 | print( str ) 57 | print( self ) 58 | 59 | print( "_label :", self._label ) 60 | print( "_rect_loc :", self._rect_loc ) 61 | 62 | print( "----------------------------------" ) 63 | 64 | return 65 | 66 | 67 | def draw_rect( self, image, color = (0,0,255), thickness = 1 ): 68 | """ 69 | バウンディングボックスの長方形を描写する。 70 | """ 71 | center_x = image.shape[0] * self._rect_loc[0] - 0.5 72 | center_y = image.shape[1] * self._rect_loc[1] - 0.5 73 | height = image.shape[1] * self._rect_loc[2] 74 | width = image.shape[0] * self._rect_loc[3] 75 | 76 | point1_x = int( center_x - width/2 ) # 長方形の左上 x 座標 77 | point1_y = int( center_y - height/2 ) # 長方形の左上 y 座標 78 | point2_x = int( center_x + width/2 ) # 長方形の右下 x 座標 79 | point2_y = int( center_y + height/2 ) # 長方形の右下 y 座標 80 | 81 | image = cv2.rectangle( 82 | img = image, 83 | pt1 = ( point1_x, point1_y ), # 長方形の左上座標 84 | pt2 = ( point2_x, point2_y ), # 長方形の右下座標 85 | color = color, # BGR 86 | thickness = thickness # 線の太さ(-1 の場合、color で設定した色で塗りつぶし) 87 | ) 88 | 89 | return image -------------------------------------------------------------------------------- /ObjectDetection_SSD_TensorFlow/model/NNActivation.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/21] : 新規作成 7 | [17/11/18] : NNActivation クラスの仕様変更。NNActivation クラスの子クラス定義 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNActivation( object ): 19 | """ 20 | ニューラルネットワークの活性化関数を表すクラス 21 | 実際の活性化関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _activate_op : 活性化関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Activation_op" ): 34 | self._activate_op = None 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNActivation" ) 41 | print( self ) 42 | print( str ) 43 | print( "_activate_op :", self._activate_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | def activate( self, input, node_name = "Activation_op" ): 49 | """ 50 | 活性化関数のオペレーターを返す。 51 | 52 | [Input] 53 | input : Operator or placeholder 54 | 活性化関数の入力となる Operatore、又は placeholder 55 | 56 | [Output] 57 | 活性化関数のオペレーター 58 | """ 59 | return self._activate_op 60 | 61 | 62 | class Sigmoid( NNActivation ): 63 | """ 64 | シグモイド関数の活性化関数 65 | NNActivation クラスの子クラスとして定義 66 | """ 67 | def __init__( self, node_name = "Activate_Sigmoid_op" ): 68 | self._activate_op = None 69 | self._node_name = node_name 70 | 71 | return 72 | 73 | def activate( self, input, node_name = "Activate_Sigmoid_op" ): 74 | self._activate_op = tf.nn.sigmoid( input, name = node_name ) 75 | self._node_name = node_name 76 | 77 | return self._activate_op 78 | 79 | 80 | class Relu( NNActivation ): 81 | """ 82 | Relu 関数の活性化関数 83 | NNActivation クラスの子クラスとして定義 84 | """ 85 | def __init__( self, node_name = "Activate_Relu_op" ): 86 | self._activate_op = None 87 | self._node_name = node_name 88 | 89 | return 90 | 91 | def activate( self, input, node_name = "Activate_Relu_op" ): 92 | self._activate_op = tf.nn.relu( input, name = node_name ) 93 | self._node_name = node_name 94 | 95 | return self._activate_op 96 | 97 | 98 | class Softmax( NNActivation ): 99 | """ 100 | softmax 関数の活性化関数 101 | NNActivation クラスの子クラスとして定義 102 | """ 103 | def __init__( self, node_name = "Activate_Softmax_op" ): 104 | self._activate_op = None 105 | self._node_name = node_name 106 | 107 | return 108 | 109 | def activate( self, input, node_name = "Activate_Softmax_op" ): 110 | self._activate_op = tf.nn.softmax( input, name = node_name ) 111 | self._node_name = node_name 112 | 113 | return self._activate_op 114 | 115 | -------------------------------------------------------------------------------- /ObjectDetection_SSD_TensorFlow/model/NNLoss.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/12/04] : 損失関数の処理の名前空間を設定するように修正 8 | [18/04/22] : シグモイド・クロス・エントロピー損失関数を表すクラス SigmoidCrossEntropy を追加 9 | [18/xx/xx] : 10 | : 11 | """ 12 | 13 | import numpy 14 | 15 | # TensorFlow ライブラリ 16 | import tensorflow as tf 17 | from tensorflow.python.framework import ops 18 | 19 | class NNLoss( object ): 20 | """ 21 | ニューラルネットワークの損失関数(評価関数、誤差関数)を表すクラス 22 | 実際の損失関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 23 | ------------------------------------------------------------------------------------------------ 24 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 25 | _loss_op : 損失関数の Operater 26 | _node_name : str 27 | この Operator ノードの名前 28 | 29 | [protedted] protedted な使用法を想定 30 | 31 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 32 | 33 | """ 34 | def __init__( self, node_name = "Loss_op" ): 35 | self._loss_op = loss( t_holder, y_out_op, node_name ) 36 | self._node_name = node_name 37 | 38 | return 39 | 40 | def print( str ): 41 | print( "NNLoss" ) 42 | print( self ) 43 | print( str ) 44 | print( "_loss_op :", self._loss_op ) 45 | print( "_node_name :", self._node_name ) 46 | 47 | return 48 | 49 | 50 | def loss( self, t_holder, y_out_op ): 51 | """ 52 | 損失関数のオペレーターを返す。 53 | 54 | [Input] 55 | _t_holder : Placeholder 56 | 教師データの Placeholder 57 | _y_out_op : Operator 58 | 出力の Operator 59 | 60 | [Output] 61 | 損失関数のオペレーター 62 | """ 63 | # 名前空間の範囲 64 | with tf.name_scope( self._node_name ): 65 | self._loss_op = None 66 | 67 | return self._loss_op 68 | 69 | 70 | class L1Norm( NNLoss ): 71 | """ 72 | L1 ノルムの損失関数 73 | NNLoss クラスの子クラスとして定義 74 | """ 75 | def __init__( self, node_name = "Loss_L1Norm_op" ): 76 | self._loss_op = None 77 | self._node_name = node_name 78 | 79 | return 80 | 81 | def loss( self, t_holder, y_out_op, node_name = "Loss_L1Norm_op" ): 82 | with tf.name_scope( self._node_name ): 83 | # tf.reduce_mean(...) でバッチサイズに対しての平均をとる。 84 | self._loss_op = tf.reduce_mean( 85 | tf.abs( t_holder - y_out_op ) 86 | ) 87 | 88 | return self._loss_op 89 | 90 | 91 | class L2Norm( NNLoss ): 92 | """ 93 | L2 ノルムの損失関数 94 | NNLoss クラスの子クラスとして定義 95 | """ 96 | def __init__( self, node_name = "Loss_L2Norm_op" ): 97 | self._loss_op = None 98 | self._node_name = node_name 99 | 100 | return 101 | 102 | def loss( self, t_holder, y_out_op, node_name = "Loss_L2Norm_op" ): 103 | with tf.name_scope( self._node_name ): 104 | self._loss_op = tf.reduce_mean( 105 | tf.square( t_holder - y_out_op ) 106 | ) 107 | 108 | return self._loss_op 109 | 110 | 111 | class BinaryCrossEntropy( NNLoss ): 112 | """ 113 | 2値のクロス・エントロピーの損失関数 114 | NNLoss クラスの子クラスとして定義 115 | """ 116 | def __init__( self, node_name = "Loss_BinaryCrossEntropy_op" ): 117 | self._loss_op = None 118 | self._node_name = node_name 119 | 120 | return 121 | 122 | def loss( self, t_holder, y_out_op ): 123 | with tf.name_scope( self._node_name ): 124 | self._loss_op = -tf.reduce_sum( 125 | t_holder * tf.log( y_out_op ) + ( 1 - t_holder ) * tf.log( 1 - y_out_op ) 126 | ) 127 | 128 | return self._loss_op 129 | 130 | 131 | class CrossEntropy( NNLoss ): 132 | """ 133 | クロス・エントロピーの損失関数 134 | NNLoss クラスの子クラスとして定義 135 | """ 136 | def __init__( self, node_name = "Loss_CrossEntropy_op" ): 137 | self._loss_op = None 138 | self._node_name = node_name 139 | 140 | return 141 | 142 | def loss( self, t_holder, y_out_op, node_name = "Loss_CrossEntropy_op" ): 143 | with tf.name_scope( self._node_name ): 144 | # softmax で正規化済みの場合 145 | # tf.clip_by_value(...) : 下限値、上限値を設定し, 値が更新されないことを防止 146 | self._loss_op = tf.reduce_mean( # ミニバッチ度に平均値を計算 147 | -tf.reduce_sum( 148 | t_holder * tf.log( tf.clip_by_value(y_out_op, 1e-10, 1.0) ), 149 | reduction_indices = [1] # sum をとる行列の方向 ( 1:row 方向 ) 150 | ) 151 | ) 152 | 153 | return self._loss_op 154 | 155 | 156 | class SigmoidCrossEntropy( NNLoss ): 157 | """ 158 | シグモイド・クロス・エントロピーの損失関数 159 | NNLoss クラスの子クラスとして定義 160 | """ 161 | def __init__( self, node_name = "Loss_SigmoidCrossEntropy_op" ): 162 | self._loss_op = None 163 | self._node_name = node_name 164 | 165 | return 166 | 167 | def loss( self, t_holder, y_out_op ): 168 | with tf.name_scope( self._node_name ): 169 | # softmax で正規化済みでない場合 170 | self._loss_op = tf.reduce_mean( 171 | tf.nn.sigmoid_cross_entropy_with_logits( 172 | labels = t_holder, 173 | logits = y_out_op 174 | ) 175 | ) 176 | 177 | return self._loss_op 178 | 179 | 180 | class SoftmaxCrossEntropy( NNLoss ): 181 | """ 182 | ソフトマックス・クロス・エントロピーの損失関数 183 | NNLoss クラスの子クラスとして定義 184 | """ 185 | def __init__( self, node_name = "Loss_SoftmaxCrossEntropy_op" ): 186 | self._loss_op = None 187 | self._node_name = node_name 188 | 189 | return 190 | 191 | def loss( self, t_holder, y_out_op ): 192 | with tf.name_scope( self._node_name ): 193 | # softmax で正規化済みでない場合 194 | self._loss_op = tf.reduce_mean( 195 | tf.nn.softmax_cross_entropy_with_logits( 196 | labels = t_holder, 197 | logits = y_out_op 198 | ) 199 | ) 200 | 201 | return self._loss_op 202 | 203 | 204 | class SparseSoftmaxCrossEntropy( NNLoss ): 205 | """ 206 | 疎なソフトマックス・クロス・エントロピーの損失関数 207 | NNLoss クラスの子クラスとして定義 208 | """ 209 | def __init__( self, node_name = "Loss_SparseSoftmaxCrossEntropy_op" ): 210 | self._loss_op = None 211 | self._node_name = node_name 212 | 213 | return 214 | 215 | def loss( self, t_holder, y_out_op ): 216 | with tf.name_scope( self._node_name ): 217 | self._loss_op = tf.reduce_mean( 218 | tf.nn.sparse_softmax_cross_entropy_with_logits( 219 | labels = t_holder, 220 | logits = y_out_op 221 | ) 222 | ) 223 | 224 | return self._loss_op 225 | 226 | 227 | -------------------------------------------------------------------------------- /ObjectDetection_SSD_TensorFlow/model/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ObjectDetection_SSD_TensorFlow/util/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ProcessingForMachineLearning_TensorFlow/main1.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | # [Anaconda Prompt] 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | # scikit-learn ライブラリ関連 18 | 19 | 20 | # 自作クラス 21 | from MLPlot import MLPlot 22 | 23 | 24 | def main(): 25 | """ 26 | ニューラルネットにおける活性化関数の実装 27 | """ 28 | print("Enter main()") 29 | 30 | #====================================================================== 31 | # ニューラルネットにおける活性化関数の実装 32 | #====================================================================== 33 | # 描写する x 軸の値の list 34 | axis_x_list = numpy.linspace( start = -10., stop = 10., num = 100 ) 35 | #print( "axis_x_list :\n", axis_x_list ) 36 | 37 | # Reset graph 38 | ops.reset_default_graph() 39 | 40 | # Session の設定 41 | session = tf.Session() 42 | 43 | # 活性化関数のオペレーション作成 44 | relu_op = tf.nn.relu( features = axis_x_list ) 45 | relu6_op = tf.nn.relu6( features = axis_x_list ) 46 | softplus_op = tf.nn.softplus( features = axis_x_list ) 47 | elu_op = tf.nn.elu( features = axis_x_list ) 48 | 49 | sigmoid_op = tf.nn.sigmoid( x = axis_x_list ) 50 | tanh_op = tf.nn.tanh( x = axis_x_list ) 51 | softsign_op = tf.nn.softsign( features = axis_x_list ) 52 | 53 | print( "tf.nn.relu(...) :\n", relu_op ) 54 | print( "tf.nn.relu6(...) :\n", relu6_op ) 55 | print( "tf.nn.softplus(...) :\n", softplus_op ) 56 | print( "tf.nn.elu(...) :\n", elu_op ) 57 | 58 | print( "tf.nn.sigmoid(...) :\n", sigmoid_op ) 59 | print( "tf.nn.tanh(...) :\n", tanh_op ) 60 | print( "tf.nn.softsign((...) :\n", softsign_op ) 61 | 62 | # Session を run してオペレーションを実行 63 | output_relu = session.run( relu_op ) 64 | output_relu6 = session.run( relu6_op ) 65 | output_softplus = session.run( softplus_op ) 66 | output_elu = session.run( elu_op ) 67 | 68 | output_sigmoid = session.run( sigmoid_op ) 69 | output_tanh = session.run( tanh_op ) 70 | output_softsign = session.run( softsign_op ) 71 | 72 | #print( "session.run( relu_op ) :\n", output_relu ) 73 | 74 | # TensorBoard 用のファイル(フォルダ)を作成 75 | # Add summaries to tensorboard 76 | #merged = tf.summary.merge_all( key='summaries' ) 77 | # tensorboard --logdir=${PWD} 78 | #summary_writer = tf.summary.FileWriter( "./TensorBoard", graph = session.graph ) 79 | 80 | session.close() 81 | 82 | #--------------------------------------- 83 | # plot activate functions 1 84 | #--------------------------------------- 85 | plt.clf() 86 | 87 | # plot Relu function 88 | plt.subplot( 2, 2, 1 ) 89 | plt.plot( 90 | axis_x_list, output_relu, 91 | label='ReLU' 92 | #linestyle = ':', 93 | #linewidth = 2, 94 | #color = 'red' 95 | ) 96 | plt.title( "Relu [Rectified Liner Unit] \n activate function" ) 97 | plt.legend( loc = 'best' ) 98 | plt.ylim( [-1.50, 10.0] ) 99 | plt.tight_layout() 100 | 101 | # plot Relu6 function 102 | plt.subplot( 2, 2, 2 ) 103 | plt.plot( 104 | axis_x_list, output_relu6, 105 | label='ReLU6' 106 | #linestyle = '--', 107 | #linewidth = 2, 108 | #color = 'blue' 109 | ) 110 | plt.title( "Relu6 \n activate function" ) 111 | plt.legend( loc = 'best' ) 112 | plt.ylim( [-1.50, 10.0] ) 113 | plt.tight_layout() 114 | 115 | # plot softplus function 116 | plt.subplot( 2, 2, 3 ) 117 | plt.plot( 118 | axis_x_list, output_softplus, 119 | label='softplus' 120 | #linestyle = '--', 121 | #linewidth = 2, 122 | #color = 'blue' 123 | ) 124 | plt.title( "softplus \n activate function" ) 125 | plt.legend( loc = 'best' ) 126 | plt.ylim( [-1.50, 10.0] ) 127 | plt.tight_layout() 128 | 129 | # plot ELU function 130 | plt.subplot( 2, 2, 4 ) 131 | plt.plot( 132 | axis_x_list, output_elu, 133 | label='ELU' 134 | #linestyle = '--', 135 | #linewidth = 2, 136 | #color = 'blue' 137 | ) 138 | plt.title( "ELU [Exponetial Liner Unit] \n activate function" ) 139 | plt.legend( loc = 'best' ) 140 | plt.ylim( [-1.50, 10.0] ) 141 | plt.tight_layout() 142 | 143 | MLPlot.saveFigure( fileName = "ProcessingForMachineLearning_TensorFlow_1-1.png" ) 144 | plt.show() 145 | 146 | #--------------------------------------- 147 | # plot activate functions 2 148 | #--------------------------------------- 149 | plt.clf() 150 | 151 | # plot sigmoid function 152 | plt.subplot( 2, 2, 1 ) 153 | plt.plot( 154 | axis_x_list, output_sigmoid, 155 | label='sigmoid' 156 | #linestyle = ':', 157 | #linewidth = 2, 158 | #color = 'red' 159 | ) 160 | plt.title( "sigmiod = 1/( 1+exp(-x) ) \n activate function" ) 161 | plt.legend( loc = 'best' ) 162 | plt.ylim( [-1.10, 1.10] ) 163 | plt.tight_layout() 164 | 165 | # plot tanh function 166 | plt.subplot( 2, 2, 2 ) 167 | plt.plot( 168 | axis_x_list, output_tanh, 169 | label='sigmoid' 170 | #linestyle = ':', 171 | #linewidth = 2, 172 | #color = 'red' 173 | ) 174 | plt.title( "tanh = ( exp(x) - exp(-x) )/( exp(x) + exp(-x) ) \n activate function" ) 175 | plt.legend( loc = 'best' ) 176 | plt.ylim( [-1.10, 1.10] ) 177 | plt.tight_layout() 178 | 179 | # plot softsign function 180 | plt.subplot( 2, 2, 3 ) 181 | plt.plot( 182 | axis_x_list, output_softsign, 183 | label='softsign' 184 | #linestyle = '--', 185 | #linewidth = 2, 186 | #color = 'blue' 187 | ) 188 | plt.title( "softsign = x/(|x|+ 1 ) \n activate function" ) 189 | plt.legend( loc = 'best' ) 190 | plt.ylim( [-1.10, 1.10] ) 191 | plt.tight_layout() 192 | 193 | MLPlot.saveFigure( fileName = "ProcessingForMachineLearning_TensorFlow_1-2.png" ) 194 | plt.show() 195 | 196 | 197 | print("Finish main()") 198 | return 199 | 200 | 201 | if __name__ == '__main__': 202 | main() -------------------------------------------------------------------------------- /ProcessingForMachineLearning_TensorFlow/main_templete.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | # 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | def main(): 18 | """ 19 | TensorFlow を用いた機械学習の基本的な処理のフレームワーク 20 | """ 21 | print("Enter main()") 22 | 23 | # Reset graph 24 | ops.reset_default_graph() 25 | 26 | # Session の設定 27 | session = tf.Session() 28 | 29 | #====================================================================== 30 | # データセットを読み込み or 生成 31 | # Import or generate data. 32 | #====================================================================== 33 | 34 | 35 | #====================================================================== 36 | # データを変換、正規化 37 | # Transform and normalize data. 38 | # ex) data = tf.nn.batch_norm_with_global_normalization(...) 39 | #====================================================================== 40 | 41 | 42 | #====================================================================== 43 | # データセットをトレーニングデータ、テストデータ、検証データセットに分割 44 | #====================================================================== 45 | 46 | 47 | #====================================================================== 48 | # アルゴリズム(モデル)のパラメータを設定 49 | # Set algorithm parameters. 50 | # ex) learning_rate = 0.01 iterations = 1000 51 | #====================================================================== 52 | 53 | 54 | #====================================================================== 55 | # 変数とプレースホルダを設定 56 | # Initialize variables and placeholders. 57 | # TensorFlow は, 損失関数を最小化するための最適化において, 58 | # 変数と重みベクトルを変更 or 調整する。 59 | # この変更や調整を実現するためには, 60 | # "プレースホルダ [placeholder]" を通じてデータを供給(フィード)する必要がある。 61 | # そして, これらの変数とプレースホルダと型について初期化する必要がある。 62 | # ex) a_var = tf.constant(42) 63 | # x_input_holder = tf.placeholder(tf.float32, [None, input_size]) 64 | # y_input_holder = tf.placeholder(tf.fload32, [None, num_classes]) 65 | #====================================================================== 66 | 67 | 68 | #====================================================================== 69 | # モデルの構造を定義する。 70 | # Define the model structure. 71 | # ex) add_op = tf.add(tf.mul(x_input_holder, weight_matrix), b_matrix) 72 | #====================================================================== 73 | 74 | 75 | #====================================================================== 76 | # 損失関数を設定する。 77 | # Declare the loss functions. 78 | #====================================================================== 79 | 80 | 81 | #====================================================================== 82 | # モデルの初期化と学習(トレーニング) 83 | # ここまでの準備で, 実際に, 計算グラフ(有向グラフ)のオブジェクトを作成し, 84 | # プレースホルダを通じて, データを計算グラフ(有向グラフ)に供給する。 85 | # Initialize and train the model. 86 | # 87 | # ex) 計算グラフを初期化する方法の1つの例 88 | # with tf.Session( graph = graph ) as session: 89 | # ... 90 | # session.run(...) 91 | # ... 92 | # session = tf.Session( graph = graph ) 93 | # session.run(…) 94 | #====================================================================== 95 | 96 | 97 | #====================================================================== 98 | # モデルの評価 99 | # (Optional) Evaluate the model. 100 | #====================================================================== 101 | 102 | 103 | #====================================================================== 104 | # ハイパーパラメータのチューニング (Optional) 105 | #====================================================================== 106 | 107 | 108 | #====================================================================== 109 | # デプロイと新しい成果指標の予想 (Optional) 110 | #====================================================================== 111 | 112 | 113 | print("Finish main()") 114 | return 115 | 116 | 117 | if __name__ == '__main__': 118 | main() -------------------------------------------------------------------------------- /Processing_TensorFlow/TensorBoard/TensorBoard_graph_PlaceHolder-Identity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/ca59e212d07daef82cd96816922005fade10690c/Processing_TensorFlow/TensorBoard/TensorBoard_graph_PlaceHolder-Identity.png -------------------------------------------------------------------------------- /Processing_TensorFlow/TensorBoard/TensorBoard_graph_Variable-Zero.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/ca59e212d07daef82cd96816922005fade10690c/Processing_TensorFlow/TensorBoard/TensorBoard_graph_Variable-Zero.png -------------------------------------------------------------------------------- /Processing_TensorFlow/TensorBoard/events.out.tfevents.1504551219.THINKPAD-T520: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/ca59e212d07daef82cd96816922005fade10690c/Processing_TensorFlow/TensorBoard/events.out.tfevents.1504551219.THINKPAD-T520 -------------------------------------------------------------------------------- /Processing_TensorFlow/TensorBoard/events.out.tfevents.1504555085.THINKPAD-T520: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/ca59e212d07daef82cd96816922005fade10690c/Processing_TensorFlow/TensorBoard/events.out.tfevents.1504555085.THINKPAD-T520 -------------------------------------------------------------------------------- /Processing_TensorFlow/main1.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | # [Anaconda Prompt] 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | def main(): 19 | """ 20 | TensorFlow を用いた基本的な処理のフレームワーク(テンプレート) 21 | """ 22 | print("Enter main()") 23 | 24 | #====================================================================== 25 | # データセットを読み込み or 生成 26 | # Import or generate data. 27 | #====================================================================== 28 | 29 | 30 | #====================================================================== 31 | # データを変換、正規化 32 | # Transform and normalize data. 33 | # ex) data = tf.nn.batch_norm_with_global_normalization(...) 34 | #====================================================================== 35 | 36 | 37 | #====================================================================== 38 | # データセットをトレーニングデータ、テストデータ、検証データセットに分割 39 | #====================================================================== 40 | 41 | 42 | #====================================================================== 43 | # アルゴリズム(モデル)のパラメータを設定 44 | # Set algorithm parameters. 45 | # ex) learning_rate = 0.01 iterations = 1000 46 | #====================================================================== 47 | 48 | 49 | #====================================================================== 50 | # 変数とプレースホルダを設定 51 | # Initialize variables and placeholders. 52 | # TensorFlow は, 損失関数を最小化するための最適化において, 53 | # 変数と重みベクトルを変更 or 調整する。 54 | # この変更や調整を実現するためには, 55 | # "プレースホルダ [placeholder]" を通じてデータを供給(フィード)する必要がある。 56 | # そして, これらの変数とプレースホルダと型について初期化する必要がある。 57 | # ex) a_var = tf.constant(42) 58 | # x_input = tf.placeholder(tf.float32, [None, input_size]) 59 | # y_input = tf.placeholder(tf.fload32, [None, num_classes]) 60 | #====================================================================== 61 | # テンソルを作成 62 | # tf.constant() : 既存の定数からテンソルを作成 63 | hello_tsr = tf.constant( "Hello, TensorFlow!" ) 64 | 65 | 66 | #====================================================================== 67 | # モデルの構造を定義する。 68 | # Define the model structure. 69 | # ex) y_pred = tf.add(tf.mul(x_input, weight_matrix), b_matrix) 70 | #====================================================================== 71 | 72 | 73 | #====================================================================== 74 | # 損失関数を設定する。 75 | # Declare the loss functions. 76 | #====================================================================== 77 | 78 | 79 | #====================================================================== 80 | # モデルの初期化と学習(トレーニング) 81 | # ここまでの準備で, 実際に, 計算グラフ(有向グラフ)のオブジェクトを作成し, 82 | # プレースホルダを通じて, データを計算グラフ(有向グラフ)に供給する。 83 | # Initialize and train the model. 84 | # 85 | # ex) 計算グラフを初期化する方法の1つの例 86 | # with tf.Session( graph = graph ) as session: 87 | # ... 88 | # session.run(...) 89 | # ... 90 | # session = tf.Session( graph = graph ) 91 | # session.run(…) 92 | #====================================================================== 93 | session = tf.Session() 94 | print( session.run( hello_tsr ) ) 95 | 96 | #====================================================================== 97 | # モデルの評価 98 | # (Optional) Evaluate the model. 99 | #====================================================================== 100 | 101 | 102 | #====================================================================== 103 | # ハイパーパラメータのチューニング (Optional) 104 | #====================================================================== 105 | 106 | 107 | #====================================================================== 108 | # デプロイと新しい成果指標の予想 (Optional) 109 | #====================================================================== 110 | 111 | 112 | print("Finish main()") 113 | return 114 | 115 | 116 | if __name__ == '__main__': 117 | main() -------------------------------------------------------------------------------- /Processing_TensorFlow/main2.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | # [Anaconda Prompt] 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops # ? 16 | 17 | 18 | def main(): 19 | """ 20 | テンソルの設定、及び計算グラフとセッション 21 | """ 22 | print("Enter main()") 23 | 24 | 25 | #====================================================================== 26 | # テンソルの設定 27 | #====================================================================== 28 | #-------------------------------------- 29 | # 固定のテンソルを作成 30 | #-------------------------------------- 31 | # tf.zeros(...) : 全ての要素が 0 からなる Tensor を作成する 32 | zeros_tsr = tf.zeros( [3, 2] ) 33 | 34 | # Session を生成せず、そのまま Tensor を print() 35 | print( " tf.zeros(...) の Tensor 型 : \n", zeros_tsr ) # <出力> 36 | # Tensor("zeros:0", shape=(3, 2), dtype=float32) 37 | # Tensor オブジェクトが出力されている。 38 | # これは session を実行していないため。 39 | 40 | # Session を生成&run() して、Tensor を print() 41 | session = tf.Session() 42 | print( session.run( zeros_tsr ) ) # <出力> 43 | # [[ 0. 0.] 44 | # [ 0. 0.] 45 | # [ 0. 0.] 46 | # 全ての要素が 0 からなる Tensor(この場合、2次配列)が出力されている。 47 | 48 | session.close() 49 | 50 | 51 | # tf.ones(...) : 全ての要素が 1 からなる Tensor を作成する 52 | ones_tsr = tf.ones( [3, 2] ) 53 | # Session を生成せず、そのまま Tensor を print() 54 | print( " tf.ones(...) の Tensor 型 : ", ones_tsr ) 55 | 56 | # Session を生成&run() して、Tensor を print() 57 | session = tf.Session() 58 | print( "tf.ones(...) の value : ", session.run( ones_tsr ) ) # <出力> 59 | # [[ 1. 1.] 60 | # [ 1. 1.] 61 | # [ 1. 1.] 62 | session.close() 63 | 64 | 65 | # tf.fill(...) : 指定した定数で埋められた Tensor を作成する。 66 | filled_tsr = tf.fill( [3, 2], "const" ) 67 | print( "tf.fill(...) の Tensor 型 : ", filled_tsr ) 68 | 69 | session = tf.Session() 70 | print( "tf.fill(...) の value : ", session.run( filled_tsr ) ) 71 | session.close() 72 | 73 | 74 | # tf.constant(...) : 指定した既存の定数から Tensor を作成する。 75 | const_tsr = tf.constant( [1,2,3] ) 76 | print( "tf.constant(...) の Tensor 型 : ", const_tsr ) 77 | 78 | session = tf.Session() 79 | print( "tf.constant(...) の value \n: ", session.run( const_tsr ) ) 80 | session.close() 81 | 82 | 83 | #-------------------------------------- 84 | # シーケンステンソルを作成 85 | #-------------------------------------- 86 | # tf.linspace(...) : stop 値のあるシーケンステンソル 87 | liner_tsr = tf.linspace( start = 0.0, stop = 1.0, num = 3 ) 88 | print( "tf.linspace(...) の Tensor 型 : ", liner_tsr ) 89 | 90 | session = tf.Session() 91 | print( "tf.linspace(...) の value : \n", session.run( liner_tsr ) ) 92 | session.close() 93 | 94 | # tf.range(...) : stop 値のないシーケンステンソル 95 | int_seq_tsr = tf.range( start = 1, limit = 15, delta = 3 ) 96 | print( "tf.range(...) の Tensor 型 : ", int_seq_tsr ) 97 | 98 | session = tf.Session() 99 | print( "tf.range(...) の value : \n", session.run( int_seq_tsr ) ) 100 | session.close() 101 | 102 | #-------------------------------------- 103 | # ランダムテンソルを作成 104 | #-------------------------------------- 105 | 106 | 107 | 108 | print("Finish main()") 109 | return 110 | 111 | 112 | if __name__ == '__main__': 113 | main() -------------------------------------------------------------------------------- /Processing_TensorFlow/main3.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | # [Anaconda Prompt] 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops # ? 16 | 17 | 18 | def main(): 19 | """ 20 | 変数とプレースホルダの設定、及び計算グラフとセッション 21 | TensorBoard でのコードの結果の計算グラフを可視化 22 | """ 23 | print("Enter main()") 24 | 25 | #====================================================================== 26 | # 変数の設定からOpノード、計算グラフの構築 27 | #====================================================================== 28 | # Reset graph 29 | ops.reset_default_graph() 30 | 31 | # Session の設定 32 | session = tf.Session() 33 | 34 | # Tensor の設定 35 | zeros_tsr = tf.zeros( [3, 2] ) 36 | 37 | # Variable の設定 38 | zeros_var = tf.Variable( zeros_tsr ) 39 | print( "tf.Variable() :", zeros_var ) 40 | 41 | # Opノード [op : operation] の作成 変数の初期化 42 | init_op = tf.global_variables_initializer() 43 | print( "tf.global_variables_initializer() :\n", init_op ) 44 | 45 | # Session を run 46 | output = session.run( init_op ) 47 | print( "session.run( init_op ) :\n", output ) 48 | 49 | # TensorBoard 用のファイル(フォルダ)を作成 50 | #merged = tf.summary.merge_all() # Add summaries to tensorboard 51 | #summary_writer = tf.summary.FileWriter( "./TensorBoard", graph = session.graph ) # tensorboard --logdir=${PWD} 52 | 53 | session.close() 54 | 55 | #====================================================================== 56 | # プレースホルダの設定からOpノード、計算グラフの構築 57 | #====================================================================== 58 | # Reset graph 59 | ops.reset_default_graph() 60 | 61 | # Session の設定 62 | session = tf.Session() 63 | 64 | # プレースホルダの作成 65 | holder = tf.placeholder( tf.float32, shape = [2, 2] ) 66 | print( "tf.placeholder( tf.float32, shape = [2, 2] ) :", holder) 67 | 68 | # 演算を設定(Opノード) 69 | identity_op = tf.identity( holder ) 70 | 71 | # 72 | random = numpy.random.rand( 2, 2 ) 73 | print( "random :", random) 74 | 75 | # 構築した計算グラフを実行 76 | output = session.run( identity_op, feed_dict = { holder : random } ) 77 | print( "session.run( identity_op, feed_dict = { holder : random } ) : \n", output ) 78 | 79 | # TensorBoard 用のファイル(フォルダ)を作成 80 | #merged = tf.summary.merge_all() # Add summaries to tensorboard 81 | #summary_writer = tf.summary.FileWriter( "./TensorBoard", graph = session.graph ) # tensorboard --logdir=${PWD} 82 | 83 | session.close() 84 | 85 | print("Finish main()") 86 | return 87 | 88 | 89 | if __name__ == '__main__': 90 | main() -------------------------------------------------------------------------------- /Processing_TensorFlow/main4.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | # [Anaconda Prompt] 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops # ? 16 | 17 | 18 | def main(): 19 | """ 20 | TensorFlow における行列の操作 21 | 22 | """ 23 | print("Enter main()") 24 | 25 | #====================================================================== 26 | # 行列の作成と操作(加算、減算等) 27 | #====================================================================== 28 | # Reset graph 29 | ops.reset_default_graph() 30 | 31 | # Session の設定 32 | session = tf.Session() 33 | 34 | # 各種行列 Tensor の作成 35 | Identity_matrix = tf.diag( [1.0, 1.0, 1.0] ) # tf.diag(...) : list から対角行列を作成 36 | A_matrix = tf.truncated_normal( [2, 3] ) # tf.truncated_normal(...) : 37 | B_matrix = tf.fill( [2,3], 5.0) # 38 | C_matrix = tf.random_uniform( [3,2] ) # tf.random_uniform(...) : 39 | D_matrix = tf.convert_to_tensor( # tf.convert_to_tensor(...) : numpy.array から Tensor を作成 40 | numpy.array( [[1., 2., 3.], [-3., -7., -1.], [0., 5., -2.]] ) 41 | ) 42 | 43 | print( "Identity_matrix : ", Identity_matrix ) 44 | print( "A_matrix : ", A_matrix ) 45 | print( "B_matrix : ", B_matrix ) 46 | print( "C_matrix : ", C_matrix ) 47 | print( "D_matrix : ", D_matrix ) 48 | 49 | # Session を run して値を設定後 print 出力 50 | print( "session.run( Identity_matrix ) :\n", session.run( Identity_matrix ) ) 51 | print( "session.run( A_matrix ) :\n", session.run( A_matrix ) ) 52 | print( "session.run( B_matrix ) :\n", session.run( B_matrix ) ) 53 | print( "session.run( C_matrix ) :\n", session.run( C_matrix ) ) 54 | print( "session.run( D_matrix ) :\n", session.run( D_matrix ) ) 55 | 56 | # 行列の加算をして print 57 | print( "A_matrix + B_marix : \n", session.run( A_matrix + B_matrix) ) 58 | 59 | # 行列の減算をして print 60 | print( "A_matrix - B_marix : \n", session.run( A_matrix - B_matrix) ) 61 | 62 | # 行列の乗算をして print 63 | print( 64 | "tf.matmul( B_matrix, Identity_matrix ) : \n", 65 | session.run( 66 | tf.matmul( B_matrix, Identity_matrix ) 67 | ) 68 | ) 69 | 70 | # TensorBoard 用のファイル(フォルダ)を作成 71 | #merged = tf.summary.merge_all() # Add summaries to tensorboard 72 | #summary_writer = tf.summary.FileWriter( "./TensorBoard", graph = session.graph ) # tensorboard --logdir=${PWD} 73 | 74 | session.close() 75 | 76 | 77 | print("Finish main()") 78 | return 79 | 80 | 81 | if __name__ == '__main__': 82 | main() -------------------------------------------------------------------------------- /Processing_TensorFlow/main5.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | # [Anaconda Prompt] 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops # ? 16 | 17 | 18 | def main(): 19 | """ 20 | TensorFlow における演算(オペレーション、Opノード)の設定、実行処理 21 | """ 22 | print("Enter main()") 23 | 24 | #====================================================================== 25 | # 演算(オペレーション、Opノード)の設定、実行 26 | #====================================================================== 27 | #---------------------------------------------------------------------- 28 | # 単一の演算(オペレーション、Opノード) 29 | #---------------------------------------------------------------------- 30 | # Reset graph 31 | ops.reset_default_graph() 32 | 33 | # Session の設定 34 | session = tf.Session() 35 | 36 | # オペレーション div 37 | # 何種類かの 割り算演算 div の動作を確認する。 38 | div_op = tf.div( 3, 4 ) # tf.div(x,y) : 整数演算での div 39 | truediv_op = tf.truediv( 3, 4 ) # tf.truediv(x,y) : 浮動小数点数に対しての div 40 | floordiv_op = tf.floordiv( 3, 4 ) # 浮動小数点数であるが、整数での演算を行いたい場合の div 41 | 42 | # Session を run してオペレーションを実行後 print 出力 43 | # 何種類かの 割り算演算 div の動作を確認する。 44 | print( "session.run( div_op ) :\n", session.run( div_op ) ) 45 | print( "session.run( truediv_op ) :\n", session.run( truediv_op ) ) 46 | print( "session.run( truediv_op ) :\n", session.run( floordiv_op ) ) 47 | 48 | 49 | # TensorBoard 用のファイル(フォルダ)を作成 50 | #merged = tf.summary.merge_all() # Add summaries to tensorboard 51 | #summary_writer = tf.summary.FileWriter( "./TensorBoard", graph = session.graph ) # tensorboard --logdir=${PWD} 52 | 53 | session.close() 54 | 55 | #---------------------------------------------------------------------- 56 | # 複数の演算(オペレーション、Opノード)の組み合わせ 57 | #---------------------------------------------------------------------- 58 | # Reset graph 59 | ops.reset_default_graph() 60 | 61 | # Session の設定 62 | session = tf.Session() 63 | 64 | # オペレーションの組み合わせ 65 | comb_tan_op = tf.div( 66 | tf.sin( 3.1416/4. ), 67 | tf.cos( 3.1416/4. ) 68 | ) 69 | 70 | cusmom_polynormal_op = cusmom_polynormal( x = 10 ) 71 | 72 | # Session を run してオペレーションを実行後 print 出力 73 | output1 = session.run( comb_tan_op ) 74 | output2 = session.run( cusmom_polynormal_op ) 75 | 76 | print( "session.run( comb_tan_op ) : ", output1 ) 77 | print( "session.run( cusmom_polynormal_op ) : ", output2 ) 78 | 79 | session.close() 80 | 81 | 82 | print("Finish main()") 83 | return 84 | 85 | def cusmom_polynormal( x ): 86 | ''' 87 | f(x) = 3 * x^2 - x + 10 88 | ''' 89 | cusmom_polynormal_op = ( tf.subtract( 3*tf.square(x), x) + 10 ) 90 | return cusmom_polynormal_op 91 | 92 | 93 | if __name__ == '__main__': 94 | main() -------------------------------------------------------------------------------- /Processing_TensorFlow/main7.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | # [Anaconda Prompt] 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops # ? 16 | 17 | 18 | def main(): 19 | """ 20 | 計算グラフでの演算(オペレーション、Opノード)の設定、実行 21 | """ 22 | print("Enter main()") 23 | 24 | #====================================================================== 25 | # 計算グラフでの演算(オペレーション、Opノード)の設定、実行 26 | #====================================================================== 27 | # Reset graph 28 | ops.reset_default_graph() 29 | 30 | # Session の設定 31 | session = tf.Session() 32 | 33 | # 各種 通常の変数、Tensor、placeholder の作成 34 | float_list = numpy.array( [1., 3., 5, 7, 9.] ) 35 | float_holder = tf.placeholder( tf.float32 ) 36 | float_const = tf.constant( 3. ) 37 | 38 | # オペレーション(Opノード)の作成 39 | multipy_op = tf.multiply( float_holder, float_const ) 40 | 41 | # 入力値の list を for ループして、list の各値に対し、オペレーション実行 42 | for value in float_list: 43 | # Session を run して、 44 | # 計算グラフに追加した placeholder をfeed_dict を通じて、オペレーション実行 45 | output = session.run( multipy_op, feed_dict = { float_holder: value } ) 46 | 47 | # Session を run した結果(Output)を print 出力 48 | print( output ) 49 | 50 | 51 | # TensorBoard 用のファイル(フォルダ)を作成 52 | # Add summaries to tensorboard 53 | #merged = tf.summary.merge_all() 54 | # tensorboard --logdir=${PWD} 55 | #summary_writer = tf.summary.FileWriter( "./TensorBoard", graph = session.graph ) 56 | 57 | session.close() 58 | 59 | 60 | print("Finish main()") 61 | return 62 | 63 | 64 | if __name__ == '__main__': 65 | main() -------------------------------------------------------------------------------- /Processing_TensorFlow/main8.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | # [Anaconda Prompt] 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops # ? 16 | 17 | 18 | def main(): 19 | """ 20 | 計算グラフでの入れ子の演算の階層化 21 | """ 22 | print("Enter main()") 23 | 24 | #====================================================================== 25 | # 計算グラフでの入れ子の演算の階層化 26 | #====================================================================== 27 | # Reset graph 28 | ops.reset_default_graph() 29 | 30 | # Session の設定 31 | session = tf.Session() 32 | 33 | # 各種 通常の変数、Tensor、placeholder の作成 34 | dim3_list = numpy.array( 35 | [ 36 | [ 1., 3., 5, 7, 9.], 37 | [-2., 0., 2., 4., 6.], 38 | [-6., -3., 0., 3., 6.] 39 | ] 40 | ) 41 | 42 | # 後の for ループでの処理のため、 43 | # 入力を2つ(2回ループ)にするため、配列を複製 44 | values = numpy.array( [dim3_list, dim3_list + 1] ) 45 | 46 | # 3*5 のデータを供給するための placeholder 47 | dim3_holder = tf.placeholder( tf.float32, shape = (3,5) ) 48 | 49 | # 行列の演算用のConst 値 50 | const1 = tf.constant( [ [1.],[0.],[-1.],[2.],[4.] ] ) 51 | const2 = tf.constant( [ [2.] ] ) 52 | const3 = tf.constant( [ [10.] ] ) 53 | 54 | print( "const1 : ", const1 ) 55 | print( "const2 : ", const2 ) 56 | print( "const3 : ", const3 ) 57 | 58 | # オペレーション(Opノード)の作成&連結 59 | matmul_op1 = tf.matmul( dim3_holder, const1 ) 60 | matmul_op2 = tf.matmul( matmul_op1, const2 ) 61 | add_op3 = tf.add( matmul_op2, const3 ) 62 | 63 | print( "tf.matmul( dim3_holder, const1 ) : ", matmul_op1 ) 64 | print( "tf.matmul( matmul_op1, const2 ) : ", matmul_op2 ) 65 | print( "tf.add( matmul_op2, const1 ) : ", add_op3 ) 66 | 67 | # 入力値の list を for ループして、list の各値に対し、 68 | # 構築した計算グラフのオペレーション実行 69 | for value in values: 70 | # Session を run して、 71 | # Placeholder から feed_dict を通じて、データを供給しながら、オペレーション実行 72 | output = session.run( add_op3, feed_dict = { dim3_holder : value } ) 73 | 74 | # Session を run した結果(Output)を print 出力 75 | print( output ) 76 | 77 | 78 | # TensorBoard 用のファイル(フォルダ)を作成 79 | # Add summaries to tensorboard 80 | #merged = tf.summary.merge_all() 81 | # tensorboard --logdir=${PWD} 82 | #summary_writer = tf.summary.FileWriter( "./TensorBoard", graph = session.graph ) 83 | 84 | session.close() 85 | 86 | 87 | print("Finish main()") 88 | return 89 | 90 | 91 | if __name__ == '__main__': 92 | main() -------------------------------------------------------------------------------- /Processing_TensorFlow/main9.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | # [Anaconda Prompt] 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | def main(): 19 | """ 20 | 計算グラフでの複数の層の追加、操作 21 | """ 22 | print("Enter main()") 23 | 24 | #====================================================================== 25 | # 計算グラフでの複数の層の追加、操作 26 | #====================================================================== 27 | # Reset graph 28 | ops.reset_default_graph() 29 | 30 | # Session の設定 31 | session = tf.Session() 32 | 33 | #------------------------------------------------- 34 | # 各種 通常の変数、Tensor、placeholder の作成 35 | #-------------------------------------------------- 36 | 37 | # 画像のデータを供給するための placeholder 38 | # 画像の形状 39 | # shape[0] : 画像の数 40 | # shape[1] : 画像の height 41 | # shape[2] : 画像の width 42 | # shape[3] : 画像の Channel 数 43 | image_shape = [ 1, 4, 4, 1 ] 44 | image_holder = tf.placeholder( tf.float32, shape = image_shape ) 45 | print( "image_holder :", image_holder ) 46 | 47 | # ランダムな画像を生成するためのランダム変数 48 | numpy.random.seed(12) 49 | random_value = numpy.random.uniform( size = image_shape ) 50 | print( "random_value : ", random_value ) 51 | 52 | # 画像のウインドウのフィルタ値、スライド値 53 | filer_const = tf.constant( 0.25, shape = [2, 2, 1, 1] ) 54 | stride_value = [1, 2, 2, 1] 55 | 56 | #---------------------------------------------------------------------- 57 | # layer(Opノード)の作成 58 | #---------------------------------------------------------------------- 59 | # 画像のウインドウに定数を "畳み込む"() 関数 60 | # 画像のウインドウの要素(ピクセル)毎に、指定したフィルタで積を求め、 61 | # 又、画像のウインドウを上下左右方向にスライドさせる。 62 | mov_avg_layer_op = tf.nn.conv2d( 63 | input = image_holder, # 64 | filter = filer_const, # 65 | strides = stride_value, # 66 | padding = "SAME", # 67 | name = "Moving_Ave_Window" # 層の名前 68 | ) 69 | 70 | print( "filer_const : ", filer_const ) 71 | print( "mov_avg_layer_op : ", mov_avg_layer_op ) 72 | 73 | # 画像のウインドウの移動平均の2×2出力を行うカスタム層を作成する。 74 | # 練習用コードの可読性のため、main() 関数内にて関数定義する。 75 | def custom_layer( input_tsr ): 76 | # tf.squeeze(...) : sizeが 1 の次元の要素を削除し次元数を減らす 77 | custom_layer_sqeezed_op = tf.squeeze( input_tsr ) 78 | 79 | A_matrix_const = tf.constant( [ [1., 2.], [-1., 3.] ] ) 80 | B_matrix_const = tf.constant( 1., shape = [2, 2] ) 81 | 82 | # オペレーション 83 | custom_layer_matmul_op = tf.matmul( A_matrix_const, custom_layer_sqeezed_op ) 84 | custom_layer_add_op = tf.add( custom_layer_matmul_op, B_matrix_const ) 85 | custom_layer_sigmoid_op = tf.sigmoid( custom_layer_add_op ) # シグモイド関数で 0 ~ 1 の範囲値に変換 86 | 87 | # オペレーションの output 値を確認 88 | output2 = session.run( custom_layer_sqeezed_op, feed_dict = { image_holder : random_value } ) 89 | output3 = session.run( custom_layer_matmul_op, feed_dict = { image_holder : random_value } ) 90 | output4 = session.run( custom_layer_add_op, feed_dict = { image_holder : random_value } ) 91 | output5 = session.run( custom_layer_sigmoid_op, feed_dict = { image_holder : random_value } ) 92 | 93 | print( "session.run( custom_layer_sqeezed_op, feed_dict = { image_holder : random_value } ) : \n", output2 ) 94 | print( "session.run( custom_layer_matmul_op, feed_dict = { image_holder : random_value } ) : \n", output2 ) 95 | print( "session.run( custom_layer_matmul_op, feed_dict = { image_holder : random_value } ) : \n", output3 ) 96 | print( "session.run( custom_layer_add_op, feed_dict = { image_holder : random_value } ) : \n", output4 ) 97 | print( "session.run( custom_layer_sigmoid_op, feed_dict = { image_holder : random_value } ) : \n", output5 ) 98 | 99 | return custom_layer_sigmoid_op 100 | 101 | # Add custom layer to graph 102 | with tf.name_scope('Custom_Layer') as scope: 103 | custom_layer_op = custom_layer( mov_avg_layer_op ) 104 | 105 | #---------------------------------------------------------------------- 106 | # 計算グラフの実行 107 | #---------------------------------------------------------------------- 108 | output1 = session.run( mov_avg_layer_op, feed_dict = { image_holder : random_value } ) 109 | output = session.run( custom_layer_op, feed_dict = { image_holder : random_value } ) 110 | 111 | print( "session.run( mov_avg_layer_op, feed_dict = { image_holder : random_value } ) : \n", output1 ) 112 | print( "session.run( custom_layer_op, feed_dict = { image_holder : random_value } ) : \n", output ) 113 | 114 | 115 | # TensorBoard 用のファイル(フォルダ)を作成 116 | # Add summaries to tensorboard 117 | #merged = tf.summary.merge_all( key='summaries' ) 118 | # tensorboard --logdir=${PWD} 119 | #summary_writer = tf.summary.FileWriter( "./TensorBoard", graph = session.graph ) 120 | 121 | session.close() 122 | 123 | 124 | print("Finish main()") 125 | return 126 | 127 | 128 | if __name__ == '__main__': 129 | main() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MachineLearning_Exercises_Python_TensorFlow 2 | Python&機械学習ライブラリ TensorFlow の使い方の練習コード集。
3 | 機械学習の中でも、特にニューラルネットワークに重点的に取り扱います。
4 | 機械学習の理論解説付きです。
5 | 6 | 分かりやすいように、各フォルダ毎で完結したコード一式になっています。
7 | 又、各フォルダにある README.md ファイルに、コード実行結果の解説と合わせて関連する機械学習の背景理論の解説も記載していきます。 8 | 9 | 10 | ### 機械学習ライブラリ : TensorFlow 11 | 12 | https://www.tensorflow.org
13 | 14 | > GitHub : 15 | >> https://github.com/tensorflow/tensorflow
16 | 17 | > チートシート:
18 | >> https://github.com/louishenrifranc/Tensorflow-Cheatsheet
19 | 20 | > API 集 :
21 | >> https://www.tensorflow.org/api_docs/python/
22 | 23 | > TensorBorad :
24 | https://deepage.net/tensorflow/2017/04/25/tensorboard.html
25 | http://tensorflow.classcat.com/2016/02/13/tensorflow-how-tos-graph-visualization/
26 | 27 | > ニューラルネットワーク :
28 | >> OverView :
29 | https://www.tensorflow.org/versions/r0.12/api_docs/python/nn/
30 | 31 | ### 検証用データセット 32 | > dataset.md 33 | >> https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/blob/master/dataset.md 34 | 35 | ## 項目(フォルダ別) 36 | 37 | 1. [./Processing_TensorFlow](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/Processing_TensorFlow) 38 | 1. [./ProcessingForMachineLearning_TensorFlow](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/ProcessingForMachineLearning_TensorFlow) 39 | 1. [./MultilayerPerceptron_TensorFlow](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/MultilayerPerceptron_TensorFlow) 40 | 1. [./CNN_TensorFlow](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/CNN_TensorFlow) 41 | 1. [./CNN_StyleNet_TensorFlow](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/CNN_StyleNet_TensorFlow) 42 | 1. [./RNN_TensorFlow](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/RNN_TensorFlow) 43 | 1. [./RNN_LSTM_TensorFlow](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/RNN_LSTM_TensorFlow) 44 | 1. [./Seq2Seq_RNN_Encoder-Decoder_TensorFlow](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/Seq2Seq_RNN_Encoder-Decoder_TensorFlow) 45 | 1. [./GAN_DCGAN_TensorFlow](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/GAN_DCGAN_TensorFlow) 46 | 1. [./ObjectDetection_SSD_TensorFlow/](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/ObjectDetection_SSD_TensorFlow) 47 | -------------------------------------------------------------------------------- /RNN_Encoder-Decoder_TensorFlow/NNActivation.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/21] : 新規作成 7 | [17/11/18] : NNActivation クラスの仕様変更。NNActivation クラスの子クラス定義 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNActivation( object ): 19 | """ 20 | ニューラルネットワークの活性化関数を表すクラス 21 | 実際の活性化関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _activate_op : 活性化関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Activation_op" ): 34 | self._activate_op = None 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNActivation" ) 41 | print( self ) 42 | print( str ) 43 | print( "_activate_op :", self._activate_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | def activate( self, input, node_name = "Activation_op" ): 49 | """ 50 | 活性化関数のオペレーターを返す。 51 | 52 | [Input] 53 | input : Operator or placeholder 54 | 活性化関数の入力となる Operatore、又は placeholder 55 | 56 | [Output] 57 | 活性化関数のオペレーター 58 | """ 59 | return self._activate_op 60 | 61 | 62 | class Sigmoid( NNActivation ): 63 | """ 64 | シグモイド関数の活性化関数 65 | NNActivation クラスの子クラスとして定義 66 | """ 67 | def __init__( self, node_name = "Activate_Sigmoid_op" ): 68 | self._activate_op = None 69 | self._node_name = node_name 70 | 71 | return 72 | 73 | def activate( self, input, node_name = "Activate_Sigmoid_op" ): 74 | self._activate_op = tf.nn.sigmoid( input, name = node_name ) 75 | self._node_name = node_name 76 | 77 | return self._activate_op 78 | 79 | 80 | class Relu( NNActivation ): 81 | """ 82 | Relu 関数の活性化関数 83 | NNActivation クラスの子クラスとして定義 84 | """ 85 | def __init__( self, node_name = "Activate_Relu_op" ): 86 | self._activate_op = None 87 | self._node_name = node_name 88 | 89 | return 90 | 91 | def activate( self, input, node_name = "Activate_Relu_op" ): 92 | self._activate_op = tf.nn.relu( input, name = node_name ) 93 | self._node_name = node_name 94 | 95 | return self._activate_op 96 | 97 | 98 | class Softmax( NNActivation ): 99 | """ 100 | softmax 関数の活性化関数 101 | NNActivation クラスの子クラスとして定義 102 | """ 103 | def __init__( self, node_name = "Activate_Softmax_op" ): 104 | self._activate_op = None 105 | self._node_name = node_name 106 | 107 | return 108 | 109 | def activate( self, input, node_name = "Activate_Softmax_op" ): 110 | self._activate_op = tf.nn.softmax( input, name = node_name ) 111 | self._node_name = node_name 112 | 113 | return self._activate_op 114 | 115 | -------------------------------------------------------------------------------- /RNN_Encoder-Decoder_TensorFlow/NNLoss.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/12/04] : 損失関数の処理の名前空間を設定するように修正 8 | [17/xx/xx] : 9 | : 10 | """ 11 | 12 | import numpy 13 | 14 | # TensorFlow ライブラリ 15 | import tensorflow as tf 16 | from tensorflow.python.framework import ops 17 | 18 | class NNLoss( object ): 19 | """ 20 | ニューラルネットワークの損失関数(評価関数、誤差関数)を表すクラス 21 | 実際の損失関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _loss_op : 損失関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Loss_op" ): 34 | self._loss_op = loss( t_holder, y_out_op, node_name ) 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNLoss" ) 41 | print( self ) 42 | print( str ) 43 | print( "_loss_op :", self._loss_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | 49 | def loss( self, t_holder, y_out_op ): 50 | """ 51 | 損失関数のオペレーターを返す。 52 | 53 | [Input] 54 | _t_holder : Placeholder 55 | 教師データの Placeholder 56 | _y_out_op : Operator 57 | 出力の Operator 58 | 59 | [Output] 60 | 損失関数のオペレーター 61 | """ 62 | # 名前空間の範囲 63 | with tf.name_scope( self._node_name ): 64 | self._loss_op = None 65 | 66 | return self._loss_op 67 | 68 | 69 | class L1Norm( NNLoss ): 70 | """ 71 | L1 ノルムの損失関数 72 | NNLoss クラスの子クラスとして定義 73 | """ 74 | def __init__( self, node_name = "Loss_L1Norm_op" ): 75 | self._loss_op = None 76 | self._node_name = node_name 77 | 78 | return 79 | 80 | def loss( self, t_holder, y_out_op, node_name = "Loss_L1Norm_op" ): 81 | with tf.name_scope( self._node_name ): 82 | # tf.reduce_mean(...) でバッチサイズに対しての平均をとる。 83 | self._loss_op = tf.reduce_mean( 84 | tf.abs( t_holder - y_out_op ) 85 | ) 86 | 87 | return self._loss_op 88 | 89 | 90 | class L2Norm( NNLoss ): 91 | """ 92 | L2 ノルムの損失関数 93 | NNLoss クラスの子クラスとして定義 94 | """ 95 | def __init__( self, node_name = "Loss_L2Norm_op" ): 96 | self._loss_op = None 97 | self._node_name = node_name 98 | 99 | return 100 | 101 | def loss( self, t_holder, y_out_op, node_name = "Loss_L2Norm_op" ): 102 | with tf.name_scope( self._node_name ): 103 | self._loss_op = tf.reduce_mean( 104 | tf.square( t_holder - y_out_op ) 105 | ) 106 | 107 | return self._loss_op 108 | 109 | 110 | class BinaryCrossEntropy( NNLoss ): 111 | """ 112 | 2値のクロス・エントロピーの損失関数 113 | NNLoss クラスの子クラスとして定義 114 | """ 115 | def __init__( self, node_name = "Loss_BinaryCrossEntropy_op" ): 116 | self._loss_op = None 117 | self._node_name = node_name 118 | 119 | return 120 | 121 | def loss( self, t_holder, y_out_op ): 122 | with tf.name_scope( self._node_name ): 123 | self._loss_op = -tf.reduce_sum( 124 | t_holder * tf.log( y_out_op ) + ( 1 - t_holder ) * tf.log( 1 - y_out_op ) 125 | ) 126 | 127 | return self._loss_op 128 | 129 | 130 | class CrossEntropy( NNLoss ): 131 | """ 132 | クロス・エントロピーの損失関数 133 | NNLoss クラスの子クラスとして定義 134 | """ 135 | def __init__( self, node_name = "Loss_CrossEntropy_op" ): 136 | self._loss_op = None 137 | self._node_name = node_name 138 | 139 | return 140 | 141 | def loss( self, t_holder, y_out_op, node_name = "Loss_CrossEntropy_op" ): 142 | with tf.name_scope( self._node_name ): 143 | # softmax で正規化済みの場合 144 | # tf.clip_by_value(...) : 下限値、上限値を設定し, 値が更新されないことを防止 145 | self._loss_op = tf.reduce_mean( # ミニバッチ度に平均値を計算 146 | -tf.reduce_sum( 147 | t_holder * tf.log( tf.clip_by_value(y_out_op, 1e-10, 1.0) ), 148 | reduction_indices = [1] # sum をとる行列の方向 ( 1:row 方向 ) 149 | ) 150 | ) 151 | 152 | return self._loss_op 153 | 154 | 155 | class SoftmaxCrossEntropy( NNLoss ): 156 | """ 157 | ソフトマックス・クロス・エントロピーの損失関数 158 | NNLoss クラスの子クラスとして定義 159 | """ 160 | def __init__( self, node_name = "Loss_SoftmaxCrossEntropy_op" ): 161 | self._loss_op = None 162 | self._node_name = node_name 163 | 164 | return 165 | 166 | def loss( self, t_holder, y_out_op ): 167 | with tf.name_scope( self._node_name ): 168 | # softmax で正規化済みでない場合 169 | self._loss_op = tf.reduce_mean( 170 | tf.nn.softmax_cross_entropy_with_logits( 171 | labels = t_holder, 172 | logits = y_out_op 173 | ) 174 | ) 175 | 176 | return self._loss_op 177 | 178 | 179 | class SparseSoftmaxCrossEntropy( NNLoss ): 180 | """ 181 | 疎なソフトマックス・クロス・エントロピーの損失関数 182 | NNLoss クラスの子クラスとして定義 183 | """ 184 | def __init__( self, node_name = "Loss_SparseSoftmaxCrossEntropy_op" ): 185 | self._loss_op = None 186 | self._node_name = node_name 187 | 188 | return 189 | 190 | def loss( self, t_holder, y_out_op ): 191 | with tf.name_scope( self._node_name ): 192 | self._loss_op = tf.reduce_mean( 193 | tf.nn.sparse_softmax_cross_entropy_with_logits( 194 | labels = t_holder, 195 | logits = y_out_op 196 | ) 197 | ) 198 | 199 | return self._loss_op 200 | 201 | 202 | -------------------------------------------------------------------------------- /RNN_Encoder-Decoder_TensorFlow/NeuralNetworkBase.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/14] : 新規作成 7 | [17/11/19] : scikit-learn ライブラリの推定器 estimator の基本クラス `BaseEstimator`, `ClassifierMixin` を継承しているように変更 8 | : 各種抽象メソッド追加 9 | [17/12/01] : TensorBoard に計算グラフを表示するためのファイルを書き込むための関数 write_tensorboard_graph(...) 追加 10 | [xx/xx/xx] : 11 | 12 | """ 13 | 14 | from abc import ABCMeta, abstractmethod # 抽象クラスを作成するための ABC クラス 15 | 16 | import numpy 17 | 18 | # scikit-learn ライブラリ関連 19 | from sklearn.base import BaseEstimator # 推定器 Estimator の上位クラス. get_params(), set_params() 関数が定義されている. 20 | from sklearn.base import ClassifierMixin # 推定器 Estimator の上位クラス. score() 関数が定義されている. 21 | 22 | # TensorFlow ライブラリ 23 | import tensorflow as tf 24 | from tensorflow.python.framework import ops 25 | 26 | import NNActivation 27 | from NNActivation import NNActivation # ニューラルネットワークの活性化関数を表すクラス 28 | from NNActivation import Sigmoid 29 | from NNActivation import Relu 30 | from NNActivation import Softmax 31 | 32 | import NNLoss # ニューラルネットワークの損失関数を表すクラス 33 | from NNLoss import L1Norm 34 | from NNLoss import L2Norm 35 | from NNLoss import BinaryCrossEntropy 36 | from NNLoss import CrossEntropy 37 | from NNLoss import SoftmaxCrossEntropy 38 | from NNLoss import SparseSoftmaxCrossEntropy 39 | 40 | import NNOptimizer # ニューラルネットワークの最適化アルゴリズム Optimizer を表すクラス 41 | from NNOptimizer import GradientDecent 42 | from NNOptimizer import Momentum 43 | from NNOptimizer import NesterovMomentum 44 | from NNOptimizer import Adagrad 45 | from NNOptimizer import Adadelta 46 | 47 | 48 | class NeuralNetworkBase( BaseEstimator, ClassifierMixin ): 49 | """ 50 | ニューラルネットワークの基底クラス(自作クラス) 51 | scikit-learn ライブラリの推定器 estimator の基本クラス BaseEstimator, ClassifierMixin を継承している. 52 | TensorFlow ライブラリを使用 53 | ニューラルネットワークの基本的なフレームワークを想定した仮想メソッドからなる抽象クラス。 54 | 実際のニューラルネットワークを表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 55 | 56 | ---------------------------------------------------------------------------------------------------- 57 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 58 | _session : tf.Session() 59 | 自身の Session 60 | _init_var_op : tf.global_variables_initializer() 61 | 全 Variable の初期化オペレーター 62 | 63 | _loss_op : Operator 64 | 損失関数を表すオペレーター 65 | _optimizer : Optimizer 66 | モデルの最適化アルゴリズム 67 | _train_step : 68 | トレーニングステップ 69 | _y_out_op : Operator 70 | モデルの出力のオペレーター 71 | 72 | [protedted] protedted な使用法を想定 73 | 74 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 75 | 76 | """ 77 | 78 | def __init__( self, session = tf.Session() ): 79 | """ 80 | コンストラクタ(厳密にはイニシャライザ) 81 | """ 82 | # メンバ変数の初期化 83 | self._session = session 84 | self._init_var_op = None 85 | 86 | self._loss_op = None 87 | self._optimizer = None 88 | self._train_step = None 89 | self._y_out_op = None 90 | 91 | return 92 | 93 | 94 | def print( self, str ): 95 | print( "NeuralNetworkBase" ) 96 | print( self ) 97 | print( str ) 98 | 99 | print( "_session : \n", self._session ) 100 | print( "_init_var_op : \n", self._init_var_op ) 101 | print( "_loss_op : \n", self._loss_op ) 102 | print( "_y_out_op : \n", self._y_out_op ) 103 | 104 | return 105 | 106 | 107 | @abstractmethod 108 | def model( self ): 109 | """ 110 | モデルの定義を行い、 111 | 最終的なモデルの出力のオペレーター self._y_out_op を設定する。 112 | (抽象メソッド) 113 | 114 | [Output] 115 | self._y_out_op : Operator 116 | モデルの出力のオペレーター 117 | """ 118 | return self._y_out_op 119 | 120 | 121 | @abstractmethod 122 | def loss( self, nnLoss ): 123 | """ 124 | 損失関数(誤差関数、コスト関数)の定義を行う。 125 | (抽象メソッド) 126 | 127 | [Input] 128 | nnLoss : NNLoss クラスのオブジェクト 129 | 130 | [Output] 131 | self._loss_op : Operator 132 | 損失関数を表すオペレーター 133 | """ 134 | return self._loss_op 135 | 136 | 137 | @abstractmethod 138 | def optimizer( self, nnOptimizer ): 139 | """ 140 | モデルの最適化アルゴリズムの設定を行う。(抽象メソッド) 141 | 142 | [Input] 143 | nnOptimizer : NNOptimizer のクラスのオブジェクト 144 | 145 | [Output] 146 | optimizer の train_step 147 | 148 | """ 149 | return self._train_step 150 | 151 | 152 | @abstractmethod 153 | def fit( self, X_train, y_train ): 154 | """ 155 | 指定されたトレーニングデータで、モデルの fitting 処理を行う。(抽象メソッド) 156 | 157 | [Input] 158 | X_train : numpy.ndarray ( shape = [n_samples, n_features] ) 159 | トレーニングデータ(特徴行列) 160 | 161 | y_train : numpy.ndarray ( shape = [n_samples] ) 162 | レーニングデータ用のクラスラベル(教師データ)のリスト 163 | 164 | [Output] 165 | self : 自身のオブジェクト 166 | """ 167 | return self 168 | 169 | 170 | @abstractmethod 171 | def predict( self, X_features ): 172 | """ 173 | fitting 処理したモデルで、推定を行い、予想値を返す。(抽象メソッド) 174 | 175 | [Input] 176 | X_features : numpy.ndarry ( shape = [n_samples, n_features] ) 177 | 予想したい特徴行列 178 | 179 | [Output] 180 | results : numpy.ndaary ( shape = [n_samples] ) 181 | 予想結果(分類モデルの場合は、クラスラベル) 182 | """ 183 | return 184 | 185 | 186 | @abstractmethod 187 | def predict_proba( self, X_test ): 188 | """ 189 | fitting 処理したモデルで、推定を行い、クラスの所属確率の予想値を返す。(抽象メソッド) 190 | proba : probability 191 | 192 | [Input] 193 | X_test : numpy.ndarry ( shape = [n_samples, n_features] ) 194 | 予想したい特徴行列 195 | """ 196 | return 197 | 198 | @abstractmethod 199 | def accuracy( self, X_test, y_test ): 200 | """ 201 | 指定したデータでの正解率 [accuracy] を計算する。 202 | """ 203 | return 204 | 205 | @abstractmethod 206 | def accuracy_labels( self, X_test, y_test ): 207 | """ 208 | 指定したデータでのラベル毎の正解率 [acuuracy] を算出する。 209 | """ 210 | return 211 | 212 | 213 | def write_tensorboard_graph( self, dir = "./TensorBoard" ): 214 | """ 215 | TensorBoard に計算グラフを表示するためのファイルを書き込む。 216 | [Input] 217 | dir : str 218 | TensorBoard 用のファイルを作成するディレクトリのパス 219 | """ 220 | # TensorBoard 用のファイル(フォルダ)を作成 221 | merged = tf.summary.merge_all() # Add summaries to tensorboard 222 | summary_writer = tf.summary.FileWriter( dir, graph = self._session.graph ) # tensorboard --logdir=${PWD} 223 | 224 | return -------------------------------------------------------------------------------- /RNN_Encoder-Decoder_TensorFlow/README.md: -------------------------------------------------------------------------------- 1 | ## TensorFlow を用いた RNN Encoder-Decoder / Sequence-to-Seuqence の実装と簡単な応用 2 | 3 | ** <18/01/31> 追記 ** 4 | 5 | ** 本フォルダの内容は、[./Seq2Seq_RNN_Encoder-Decoder_TensorFlow](https://github.com/Yagami360/MachineLearning_Exercises_Python_TensorFlow/tree/master/Seq2Seq_RNN_Encoder-Decoder_TensorFlow) に移行してあります。 ** -------------------------------------------------------------------------------- /RNN_Encoder-Decoder_TensorFlow/main2.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 5.0.1 環境 (TensorFlow インストール済み) 3 | # 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | # 自作クラス 18 | from MLPreProcess import MLPreProcess 19 | from MLPlot import MLPlot 20 | 21 | import NNActivation # ニューラルネットワークの活性化関数を表すクラス 22 | from NNActivation import NNActivation 23 | from NNActivation import Sigmoid 24 | from NNActivation import Relu 25 | from NNActivation import Softmax 26 | 27 | import NNLoss # ニューラルネットワークの損失関数を表すクラス 28 | from NNLoss import L1Norm 29 | from NNLoss import L2Norm 30 | from NNLoss import BinaryCrossEntropy 31 | from NNLoss import CrossEntropy 32 | from NNLoss import SoftmaxCrossEntropy 33 | from NNLoss import SparseSoftmaxCrossEntropy 34 | 35 | import NNOptimizer # ニューラルネットワークの最適化アルゴリズム Optimizer を表すクラス 36 | from NNOptimizer import GradientDecent 37 | from NNOptimizer import GradientDecentDecay 38 | from NNOptimizer import Momentum 39 | from NNOptimizer import NesterovMomentum 40 | from NNOptimizer import Adagrad 41 | from NNOptimizer import Adadelta 42 | from NNOptimizer import Adam 43 | 44 | from NeuralNetworkBase import NeuralNetworkBase 45 | from RecurrectNNEncoderDecoderLSTM import RecurrectNNEncoderDecoderLSTM 46 | from RecurrectNNEncoderDecoderEmbeddingLSTM import RecurrectNNEncoderDecoderEmbeddingLSTM 47 | 48 | 49 | def main(): 50 | """ 51 | TensorFlow を用いた RNN Encoder-Decoder(LSTM 使用) によるシェイクスピア作品のワード予想処理 52 | """ 53 | print("Enter main()") 54 | 55 | # Reset graph 56 | #ops.reset_default_graph() 57 | 58 | #====================================================================== 59 | # データセットを読み込み or 生成 60 | # Import or generate data. 61 | #====================================================================== 62 | path_text = "C:\Data\MachineLearning_DataSet\Project_Gutenberg\William_Shakespeare\pg100.txt" 63 | 64 | # The Project Gutenberg EBook にある、シェイクスピア作品のテキストデータの読み込み&抽出処理 65 | text_data = MLPreProcess.load_textdata_by_shakespeare_from_theProjectGutenbergEBook( path = path_text, n_DeleteParagraph = 182, bCleaning = True ) 66 | #print( "text_data :\n", text_data ) 67 | 68 | # 抽出したテキストデータから、出現頻度の高い単語をディクショナリに登録する 69 | # 抽出したテキストデータを、このディクショナリに基づき、数値インデックス情報に変換する。 70 | text_data_idx, n_vocab = MLPreProcess.text_vocabulary_processing_without_tensorflow( text_data , min_word_freq = 5 ) 71 | print( "text_data_idx :", text_data_idx ) 72 | print( "len( text_data_idx ) :", len( text_data_idx ) ) 73 | print( "n_vocab :", n_vocab ) 74 | 75 | #====================================================================== 76 | # データを変換、正規化 77 | # Transform and normalize data. 78 | # ex) data = tf.nn.batch_norm_with_global_normalization(...) 79 | #====================================================================== 80 | 81 | 82 | #====================================================================== 83 | # データセットをトレーニングデータ、テストデータ、検証データセットに分割 84 | #====================================================================== 85 | 86 | 87 | #====================================================================== 88 | # アルゴリズム(モデル)のパラメータを設定 89 | # Set algorithm parameters. 90 | # ex) learning_rate = 0.01 iterations = 1000 91 | #====================================================================== 92 | learning_rate1 = 0.001 93 | adam_beta1 = 0.9 # For the Adam optimizer 94 | adam_beta2 = 0.999 # For the Adam optimizer 95 | 96 | rnn1 = RecurrectNNEncoderDecoderEmbeddingLSTM( 97 | session = tf.Session(), 98 | n_inputLayer = 1, 99 | n_hiddenLayer = 128, # rnn_size 100 | n_outputLayer = 1, 101 | n_in_sequence_encoder = 50, # エンコーダー側のシーケンス長 / 102 | n_in_sequence_decoder = 50, # デコーダー側のシーケンス長 / 103 | n_vocab = n_vocab, # 7511 104 | epochs = 1000, 105 | batch_size = 100, 106 | eval_step = 1, 107 | save_step = 500 108 | ) 109 | rnn1.print( "after __init__()" ) 110 | 111 | #====================================================================== 112 | # 変数とプレースホルダを設定 113 | # Initialize variables and placeholders. 114 | # TensorFlow は, 損失関数を最小化するための最適化において, 115 | # 変数と重みベクトルを変更 or 調整する。 116 | # この変更や調整を実現するためには, 117 | # "プレースホルダ [placeholder]" を通じてデータを供給(フィード)する必要がある。 118 | # そして, これらの変数とプレースホルダと型について初期化する必要がある。 119 | # ex) a_tsr = tf.constant(42) 120 | # x_input_holder = tf.placeholder(tf.float32, [None, input_size]) 121 | # y_input_holder = tf.placeholder(tf.fload32, [None, num_classes]) 122 | #====================================================================== 123 | 124 | 125 | #====================================================================== 126 | # モデルの構造を定義する。 127 | # Define the model structure. 128 | # ex) add_op = tf.add(tf.mul(x_input_holder, weight_matrix), b_matrix) 129 | #====================================================================== 130 | rnn1.model() 131 | rnn1.print( "after model()" ) 132 | 133 | #====================================================================== 134 | # 損失関数を設定する。 135 | # Declare the loss functions. 136 | #====================================================================== 137 | #rnn1.loss( L2Norm() ) 138 | 139 | #====================================================================== 140 | # モデルの最適化アルゴリズム Optimizer を設定する。 141 | # Declare Optimizer. 142 | #====================================================================== 143 | #rnn1.optimizer( Adam( learning_rate = learning_rate1, beta1 = adam_beta1, beta2 = adam_beta2 ) ) 144 | 145 | #====================================================================== 146 | # モデルの初期化と学習(トレーニング) 147 | # ここまでの準備で, 実際に, 計算グラフ(有向グラフ)のオブジェクトを作成し, 148 | # プレースホルダを通じて, データを計算グラフ(有向グラフ)に供給する。 149 | # Initialize and train the model. 150 | # 151 | # ex) 計算グラフを初期化する方法の1つの例 152 | # with tf.Session( graph = graph ) as session: 153 | # ... 154 | # session.run(...) 155 | # ... 156 | # session = tf.Session( graph = graph ) 157 | # session.run(…) 158 | #====================================================================== 159 | # TensorBoard 用のファイル(フォルダ)を作成 160 | #rnn1.write_tensorboard_graph() 161 | 162 | # fitting 処理を行う 163 | #rnn1.fit( X_train, y_train ) 164 | #rnn1.print( "after fitting" ) 165 | 166 | #====================================================================== 167 | # モデルの評価 168 | # (Optional) Evaluate the model. 169 | #====================================================================== 170 | #--------------------------------------------------------- 171 | # 損失関数を plot 172 | #--------------------------------------------------------- 173 | """ 174 | plt.clf() 175 | plt.plot( 176 | range( rnn1._epochs ), rnn1._losses_train, 177 | label = 'RNN - %s = [%d - %d - %d], learning_rate = %0.3f' % ( type(rnn1) , rnn1._n_inputLayer, rnn1._n_hiddenLayer, rnn1._n_outputLayer, learning_rate1 ) , 178 | linestyle = '-', 179 | linewidth = 0.2, 180 | color = 'red' 181 | ) 182 | plt.title( "loss / L2 Norm (MSE)" ) 183 | plt.legend( loc = 'best' ) 184 | plt.ylim( ymin = 0.0 ) 185 | plt.xlabel( "Epocs" ) 186 | plt.grid() 187 | plt.tight_layout() 188 | 189 | MLPlot.saveFigure( fileName = "RNN-LSTM_3-1.png" ) 190 | plt.show() 191 | """ 192 | #--------------------------------------------------------- 193 | # 予想値 194 | #--------------------------------------------------------- 195 | # 予想値を取得 196 | #predicts1 = rnn1.predict( X_features ) 197 | #print( "predicts1 :\n", predicts1 ) 198 | 199 | 200 | #====================================================================== 201 | # ハイパーパラメータのチューニング (Optional) 202 | #====================================================================== 203 | 204 | 205 | #====================================================================== 206 | # デプロイと新しい成果指標の予想 (Optional) 207 | #====================================================================== 208 | 209 | 210 | print("Finish main()") 211 | return 212 | 213 | 214 | if __name__ == '__main__': 215 | main() 216 | -------------------------------------------------------------------------------- /RNN_LSTM_TensorFlow/NNActivation.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/21] : 新規作成 7 | [17/11/18] : NNActivation クラスの仕様変更。NNActivation クラスの子クラス定義 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNActivation( object ): 19 | """ 20 | ニューラルネットワークの活性化関数を表すクラス 21 | 実際の活性化関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _activate_op : 活性化関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Activation_op" ): 34 | self._activate_op = None 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNActivation" ) 41 | print( self ) 42 | print( str ) 43 | print( "_activate_op :", self._activate_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | def activate( self, input, node_name = "Activation_op" ): 49 | """ 50 | 活性化関数のオペレーターを返す。 51 | 52 | [Input] 53 | input : Operator or placeholder 54 | 活性化関数の入力となる Operatore、又は placeholder 55 | 56 | [Output] 57 | 活性化関数のオペレーター 58 | """ 59 | return self._activate_op 60 | 61 | 62 | class Sigmoid( NNActivation ): 63 | """ 64 | シグモイド関数の活性化関数 65 | NNActivation クラスの子クラスとして定義 66 | """ 67 | def __init__( self, node_name = "Activate_Sigmoid_op" ): 68 | self._activate_op = None 69 | self._node_name = node_name 70 | 71 | return 72 | 73 | def activate( self, input, node_name = "Activate_Sigmoid_op" ): 74 | self._activate_op = tf.nn.sigmoid( input, name = node_name ) 75 | self._node_name = node_name 76 | 77 | return self._activate_op 78 | 79 | 80 | class Relu( NNActivation ): 81 | """ 82 | Relu 関数の活性化関数 83 | NNActivation クラスの子クラスとして定義 84 | """ 85 | def __init__( self, node_name = "Activate_Relu_op" ): 86 | self._activate_op = None 87 | self._node_name = node_name 88 | 89 | return 90 | 91 | def activate( self, input, node_name = "Activate_Relu_op" ): 92 | self._activate_op = tf.nn.relu( input, name = node_name ) 93 | self._node_name = node_name 94 | 95 | return self._activate_op 96 | 97 | 98 | class Softmax( NNActivation ): 99 | """ 100 | softmax 関数の活性化関数 101 | NNActivation クラスの子クラスとして定義 102 | """ 103 | def __init__( self, node_name = "Activate_Softmax_op" ): 104 | self._activate_op = None 105 | self._node_name = node_name 106 | 107 | return 108 | 109 | def activate( self, input, node_name = "Activate_Softmax_op" ): 110 | self._activate_op = tf.nn.softmax( input, name = node_name ) 111 | self._node_name = node_name 112 | 113 | return self._activate_op 114 | 115 | -------------------------------------------------------------------------------- /RNN_LSTM_TensorFlow/NNLoss.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/12/04] : 損失関数の処理の名前空間を設定するように修正 8 | [18/04/22] : シグモイド・クロス・エントロピー損失関数を表すクラス SigmoidCrossEntropy を追加 9 | [18/xx/xx] : 10 | : 11 | """ 12 | 13 | import numpy 14 | 15 | # TensorFlow ライブラリ 16 | import tensorflow as tf 17 | from tensorflow.python.framework import ops 18 | 19 | class NNLoss( object ): 20 | """ 21 | ニューラルネットワークの損失関数(評価関数、誤差関数)を表すクラス 22 | 実際の損失関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 23 | ------------------------------------------------------------------------------------------------ 24 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 25 | _loss_op : 損失関数の Operater 26 | _node_name : str 27 | この Operator ノードの名前 28 | 29 | [protedted] protedted な使用法を想定 30 | 31 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 32 | 33 | """ 34 | def __init__( self, node_name = "Loss_op" ): 35 | self._loss_op = loss( t_holder, y_out_op, node_name ) 36 | self._node_name = node_name 37 | 38 | return 39 | 40 | def print( str ): 41 | print( "NNLoss" ) 42 | print( self ) 43 | print( str ) 44 | print( "_loss_op :", self._loss_op ) 45 | print( "_node_name :", self._node_name ) 46 | 47 | return 48 | 49 | 50 | def loss( self, t_holder, y_out_op ): 51 | """ 52 | 損失関数のオペレーターを返す。 53 | 54 | [Input] 55 | _t_holder : Placeholder 56 | 教師データの Placeholder 57 | _y_out_op : Operator 58 | 出力の Operator 59 | 60 | [Output] 61 | 損失関数のオペレーター 62 | """ 63 | # 名前空間の範囲 64 | with tf.name_scope( self._node_name ): 65 | self._loss_op = None 66 | 67 | return self._loss_op 68 | 69 | 70 | class L1Norm( NNLoss ): 71 | """ 72 | L1 ノルムの損失関数 73 | NNLoss クラスの子クラスとして定義 74 | """ 75 | def __init__( self, node_name = "Loss_L1Norm_op" ): 76 | self._loss_op = None 77 | self._node_name = node_name 78 | 79 | return 80 | 81 | def loss( self, t_holder, y_out_op, node_name = "Loss_L1Norm_op" ): 82 | with tf.name_scope( self._node_name ): 83 | # tf.reduce_mean(...) でバッチサイズに対しての平均をとる。 84 | self._loss_op = tf.reduce_mean( 85 | tf.abs( t_holder - y_out_op ) 86 | ) 87 | 88 | return self._loss_op 89 | 90 | 91 | class L2Norm( NNLoss ): 92 | """ 93 | L2 ノルムの損失関数 94 | NNLoss クラスの子クラスとして定義 95 | """ 96 | def __init__( self, node_name = "Loss_L2Norm_op" ): 97 | self._loss_op = None 98 | self._node_name = node_name 99 | 100 | return 101 | 102 | def loss( self, t_holder, y_out_op, node_name = "Loss_L2Norm_op" ): 103 | with tf.name_scope( self._node_name ): 104 | self._loss_op = tf.reduce_mean( 105 | tf.square( t_holder - y_out_op ) 106 | ) 107 | 108 | return self._loss_op 109 | 110 | 111 | class BinaryCrossEntropy( NNLoss ): 112 | """ 113 | 2値のクロス・エントロピーの損失関数 114 | NNLoss クラスの子クラスとして定義 115 | """ 116 | def __init__( self, node_name = "Loss_BinaryCrossEntropy_op" ): 117 | self._loss_op = None 118 | self._node_name = node_name 119 | 120 | return 121 | 122 | def loss( self, t_holder, y_out_op ): 123 | with tf.name_scope( self._node_name ): 124 | self._loss_op = -tf.reduce_sum( 125 | t_holder * tf.log( y_out_op ) + ( 1 - t_holder ) * tf.log( 1 - y_out_op ) 126 | ) 127 | 128 | return self._loss_op 129 | 130 | 131 | class CrossEntropy( NNLoss ): 132 | """ 133 | クロス・エントロピーの損失関数 134 | NNLoss クラスの子クラスとして定義 135 | """ 136 | def __init__( self, node_name = "Loss_CrossEntropy_op" ): 137 | self._loss_op = None 138 | self._node_name = node_name 139 | 140 | return 141 | 142 | def loss( self, t_holder, y_out_op, node_name = "Loss_CrossEntropy_op" ): 143 | with tf.name_scope( self._node_name ): 144 | # softmax で正規化済みの場合 145 | # tf.clip_by_value(...) : 下限値、上限値を設定し, 値が更新されないことを防止 146 | self._loss_op = tf.reduce_mean( # ミニバッチ度に平均値を計算 147 | -tf.reduce_sum( 148 | t_holder * tf.log( tf.clip_by_value(y_out_op, 1e-10, 1.0) ), 149 | reduction_indices = [1] # sum をとる行列の方向 ( 1:row 方向 ) 150 | ) 151 | ) 152 | 153 | return self._loss_op 154 | 155 | 156 | class SigmoidCrossEntropy( NNLoss ): 157 | """ 158 | シグモイド・クロス・エントロピーの損失関数 159 | NNLoss クラスの子クラスとして定義 160 | """ 161 | def __init__( self, node_name = "Loss_SigmoidCrossEntropy_op" ): 162 | self._loss_op = None 163 | self._node_name = node_name 164 | 165 | return 166 | 167 | def loss( self, t_holder, y_out_op ): 168 | with tf.name_scope( self._node_name ): 169 | # softmax で正規化済みでない場合 170 | self._loss_op = tf.reduce_mean( 171 | tf.nn.sigmoid_cross_entropy_with_logits( 172 | labels = t_holder, 173 | logits = y_out_op 174 | ) 175 | ) 176 | 177 | return self._loss_op 178 | 179 | 180 | class SoftmaxCrossEntropy( NNLoss ): 181 | """ 182 | ソフトマックス・クロス・エントロピーの損失関数 183 | NNLoss クラスの子クラスとして定義 184 | """ 185 | def __init__( self, node_name = "Loss_SoftmaxCrossEntropy_op" ): 186 | self._loss_op = None 187 | self._node_name = node_name 188 | 189 | return 190 | 191 | def loss( self, t_holder, y_out_op ): 192 | with tf.name_scope( self._node_name ): 193 | # softmax で正規化済みでない場合 194 | self._loss_op = tf.reduce_mean( 195 | tf.nn.softmax_cross_entropy_with_logits( 196 | labels = t_holder, 197 | logits = y_out_op 198 | ) 199 | ) 200 | 201 | return self._loss_op 202 | 203 | 204 | class SparseSoftmaxCrossEntropy( NNLoss ): 205 | """ 206 | 疎なソフトマックス・クロス・エントロピーの損失関数 207 | NNLoss クラスの子クラスとして定義 208 | """ 209 | def __init__( self, node_name = "Loss_SparseSoftmaxCrossEntropy_op" ): 210 | self._loss_op = None 211 | self._node_name = node_name 212 | 213 | return 214 | 215 | def loss( self, t_holder, y_out_op ): 216 | with tf.name_scope( self._node_name ): 217 | self._loss_op = tf.reduce_mean( 218 | tf.nn.sparse_softmax_cross_entropy_with_logits( 219 | labels = t_holder, 220 | logits = y_out_op 221 | ) 222 | ) 223 | 224 | return self._loss_op 225 | 226 | 227 | -------------------------------------------------------------------------------- /RNN_LSTM_TensorFlow/NeuralNetworkBase.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/14] : 新規作成 7 | [17/11/19] : scikit-learn ライブラリの推定器 estimator の基本クラス `BaseEstimator`, `ClassifierMixin` を継承しているように変更 8 | : 各種抽象メソッド追加 9 | [17/12/01] : TensorBoard に計算グラフを表示するためのファイルを書き込むための関数 write_tensorboard_graph(...) 追加 10 | [xx/xx/xx] : 11 | 12 | """ 13 | 14 | from abc import ABCMeta, abstractmethod # 抽象クラスを作成するための ABC クラス 15 | 16 | import numpy 17 | 18 | # scikit-learn ライブラリ関連 19 | from sklearn.base import BaseEstimator # 推定器 Estimator の上位クラス. get_params(), set_params() 関数が定義されている. 20 | from sklearn.base import ClassifierMixin # 推定器 Estimator の上位クラス. score() 関数が定義されている. 21 | 22 | # TensorFlow ライブラリ 23 | import tensorflow as tf 24 | from tensorflow.python.framework import ops 25 | 26 | import NNActivation 27 | from NNActivation import NNActivation # ニューラルネットワークの活性化関数を表すクラス 28 | from NNActivation import Sigmoid 29 | from NNActivation import Relu 30 | from NNActivation import Softmax 31 | 32 | import NNLoss # ニューラルネットワークの損失関数を表すクラス 33 | from NNLoss import L1Norm 34 | from NNLoss import L2Norm 35 | from NNLoss import BinaryCrossEntropy 36 | from NNLoss import CrossEntropy 37 | from NNLoss import SoftmaxCrossEntropy 38 | from NNLoss import SparseSoftmaxCrossEntropy 39 | 40 | import NNOptimizer # ニューラルネットワークの最適化アルゴリズム Optimizer を表すクラス 41 | from NNOptimizer import GradientDecent 42 | from NNOptimizer import Momentum 43 | from NNOptimizer import NesterovMomentum 44 | from NNOptimizer import Adagrad 45 | from NNOptimizer import Adadelta 46 | 47 | 48 | class NeuralNetworkBase( BaseEstimator, ClassifierMixin ): 49 | """ 50 | ニューラルネットワークの基底クラス(自作クラス) 51 | scikit-learn ライブラリの推定器 estimator の基本クラス BaseEstimator, ClassifierMixin を継承している. 52 | TensorFlow ライブラリを使用 53 | ニューラルネットワークの基本的なフレームワークを想定した仮想メソッドからなる抽象クラス。 54 | 実際のニューラルネットワークを表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 55 | 56 | ---------------------------------------------------------------------------------------------------- 57 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 58 | _session : tf.Session() 59 | 自身の Session 60 | _init_var_op : tf.global_variables_initializer() 61 | 全 Variable の初期化オペレーター 62 | 63 | _loss_op : Operator 64 | 損失関数を表すオペレーター 65 | _optimizer : Optimizer 66 | モデルの最適化アルゴリズム 67 | _train_step : 68 | トレーニングステップ 69 | _y_out_op : Operator 70 | モデルの出力のオペレーター 71 | 72 | [protedted] protedted な使用法を想定 73 | 74 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 75 | 76 | """ 77 | 78 | def __init__( self, session = tf.Session() ): 79 | """ 80 | コンストラクタ(厳密にはイニシャライザ) 81 | """ 82 | # メンバ変数の初期化 83 | self._session = session 84 | self._init_var_op = None 85 | 86 | self._loss_op = None 87 | self._optimizer = None 88 | self._train_step = None 89 | self._y_out_op = None 90 | 91 | return 92 | 93 | 94 | def print( self, str ): 95 | print( "NeuralNetworkBase" ) 96 | print( self ) 97 | print( str ) 98 | 99 | print( "_session : \n", self._session ) 100 | print( "_init_var_op : \n", self._init_var_op ) 101 | print( "_loss_op : \n", self._loss_op ) 102 | print( "_y_out_op : \n", self._y_out_op ) 103 | 104 | return 105 | 106 | 107 | @abstractmethod 108 | def model( self ): 109 | """ 110 | モデルの定義を行い、 111 | 最終的なモデルの出力のオペレーター self._y_out_op を設定する。 112 | (抽象メソッド) 113 | 114 | [Output] 115 | self._y_out_op : Operator 116 | モデルの出力のオペレーター 117 | """ 118 | return self._y_out_op 119 | 120 | 121 | @abstractmethod 122 | def loss( self, nnLoss ): 123 | """ 124 | 損失関数(誤差関数、コスト関数)の定義を行う。 125 | (抽象メソッド) 126 | 127 | [Input] 128 | nnLoss : NNLoss クラスのオブジェクト 129 | 130 | [Output] 131 | self._loss_op : Operator 132 | 損失関数を表すオペレーター 133 | """ 134 | return self._loss_op 135 | 136 | 137 | @abstractmethod 138 | def optimizer( self, nnOptimizer ): 139 | """ 140 | モデルの最適化アルゴリズムの設定を行う。(抽象メソッド) 141 | 142 | [Input] 143 | nnOptimizer : NNOptimizer のクラスのオブジェクト 144 | 145 | [Output] 146 | optimizer の train_step 147 | 148 | """ 149 | return self._train_step 150 | 151 | 152 | @abstractmethod 153 | def fit( self, X_train, y_train ): 154 | """ 155 | 指定されたトレーニングデータで、モデルの fitting 処理を行う。(抽象メソッド) 156 | 157 | [Input] 158 | X_train : numpy.ndarray ( shape = [n_samples, n_features] ) 159 | トレーニングデータ(特徴行列) 160 | 161 | y_train : numpy.ndarray ( shape = [n_samples] ) 162 | レーニングデータ用のクラスラベル(教師データ)のリスト 163 | 164 | [Output] 165 | self : 自身のオブジェクト 166 | """ 167 | return self 168 | 169 | 170 | @abstractmethod 171 | def predict( self, X_features ): 172 | """ 173 | fitting 処理したモデルで、推定を行い、予想値を返す。(抽象メソッド) 174 | 175 | [Input] 176 | X_features : numpy.ndarry ( shape = [n_samples, n_features] ) 177 | 予想したい特徴行列 178 | 179 | [Output] 180 | results : numpy.ndaary ( shape = [n_samples] ) 181 | 予想結果(分類モデルの場合は、クラスラベル) 182 | """ 183 | return 184 | 185 | 186 | @abstractmethod 187 | def predict_proba( self, X_test ): 188 | """ 189 | fitting 処理したモデルで、推定を行い、クラスの所属確率の予想値を返す。(抽象メソッド) 190 | proba : probability 191 | 192 | [Input] 193 | X_test : numpy.ndarry ( shape = [n_samples, n_features] ) 194 | 予想したい特徴行列 195 | """ 196 | return 197 | 198 | @abstractmethod 199 | def accuracy( self, X_test, y_test ): 200 | """ 201 | 指定したデータでの正解率 [accuracy] を計算する。 202 | """ 203 | return 204 | 205 | @abstractmethod 206 | def accuracy_labels( self, X_test, y_test ): 207 | """ 208 | 指定したデータでのラベル毎の正解率 [acuuracy] を算出する。 209 | """ 210 | return 211 | 212 | 213 | def write_tensorboard_graph( self, dir = "./TensorBoard" ): 214 | """ 215 | TensorBoard に計算グラフを表示するためのファイルを書き込む。 216 | [Input] 217 | dir : str 218 | TensorBoard 用のファイルを作成するディレクトリのパス 219 | """ 220 | # TensorBoard 用のファイル(フォルダ)を作成 221 | merged = tf.summary.merge_all() # Add summaries to tensorboard 222 | summary_writer = tf.summary.FileWriter( dir, graph = self._session.graph ) # tensorboard --logdir=${PWD} 223 | 224 | return -------------------------------------------------------------------------------- /RNN_LSTM_TensorFlow/RecurrentNNLSTM.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 5.0.1 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/12/01] : 新規作成 7 | [xx/xx/xx] : 8 | 9 | """ 10 | import numpy 11 | 12 | # TensorFlow ライブラリ 13 | import tensorflow as tf 14 | from tensorflow.python.framework import ops 15 | 16 | # scikit-learn ライブラリ 17 | from sklearn.utils import shuffle 18 | 19 | # 自作クラス 20 | from NeuralNetworkBase import NeuralNetworkBase # 親クラス 21 | from RecurrentNN import RecurrentNN 22 | 23 | import NNActivation 24 | from NNActivation import NNActivation # ニューラルネットワークの活性化関数を表すクラス 25 | from NNActivation import Sigmoid 26 | from NNActivation import Relu 27 | from NNActivation import Softmax 28 | 29 | import NNLoss # ニューラルネットワークの損失関数を表すクラス 30 | from NNLoss import L1Norm 31 | from NNLoss import L2Norm 32 | from NNLoss import BinaryCrossEntropy 33 | from NNLoss import CrossEntropy 34 | from NNLoss import SoftmaxCrossEntropy 35 | from NNLoss import SparseSoftmaxCrossEntropy 36 | 37 | import NNOptimizer # ニューラルネットワークの最適化アルゴリズム Optimizer を表すクラス 38 | from NNOptimizer import GradientDecent 39 | from NNOptimizer import Momentum 40 | from NNOptimizer import NesterovMomentum 41 | from NNOptimizer import Adagrad 42 | from NNOptimizer import Adadelta 43 | from NNOptimizer import Adam 44 | 45 | 46 | class RecurrentNNLSTM( RecurrentNN ): 47 | """ 48 | リカレントニューラルネットワーク [RNN : Recurrent Neural Network] の 49 | [LSTM : Long short-term memory](長短期記憶モデル)を表すクラス。 50 | TensorFlow での RNN の処理をクラス(任意の層に DNN 化可能な柔軟なクラス)でラッピングし、 51 | scikit-learn ライブラリの classifier, estimator とインターフェイスを共通化することで、 52 | scikit-learn ライブラリとの互換性のある自作クラス 53 | ------------------------------------------------------------------------------------------------ 54 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 55 | _rnn_cells : list 56 | RNN 構造を提供する cell のリスト 57 | この `cell` は、内部(プロパティ)で state(隠れ層の状態)を保持しており、 58 | これを次の時間の隠れ層に順々に渡していくことで、時間軸の逆伝搬を実現する。 59 | _rnn_states : list 60 | cell の状態 61 | 62 | [protedted] protedted な使用法を想定 63 | 64 | 65 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 66 | 67 | """ 68 | 69 | def __init__( 70 | self, 71 | session = tf.Session( config = tf.ConfigProto(log_device_placement=True) ), 72 | n_inputLayer = 1, n_hiddenLayer = 1, n_outputLayer = 1, 73 | n_in_sequence = 25, 74 | epochs = 1000, 75 | batch_size = 10, 76 | eval_step = 1 77 | ): 78 | """ 79 | コンストラクタ(厳密にはイニシャライザ) 80 | """ 81 | # 親クラスである ReccurentRNN クラスのコンストラクタ呼び出し 82 | super().__init__( session, n_inputLayer, n_hiddenLayer, n_outputLayer, n_in_sequence, epochs, batch_size, eval_step ) 83 | 84 | return 85 | 86 | 87 | def model( self ): 88 | """ 89 | モデルの定義(計算グラフの構築)を行い、 90 | 最終的なモデルの出力のオペレーターを設定する。 91 | 92 | [Output] 93 | self._y_out_op : Operator 94 | モデルの出力のオペレーター 95 | """ 96 | #-------------------------------------------------------------- 97 | # 入力層 ~ 隠れ層 98 | #-------------------------------------------------------------- 99 | # tf.contrib.rnn.LSTMCell(...) : 時系列に沿った RNN 構造を提供するクラス `LSTMCell` のオブジェクト cell を返す。 100 | # この cell は、内部(プロパティ)で state(隠れ層の状態)を保持しており、 101 | # これを次の時間の隠れ層に順々に渡していくことで、時間軸の逆伝搬を実現する。 102 | cell = tf.contrib.rnn.LSTMCell( 103 | num_units = self._n_hiddenLayer, # int, The number of units in the RNN cell. 104 | forget_bias = 1.0 # 忘却ゲートのバイアス項 / Default : 1.0 in order to reduce the scale of forgetting at the beginning of the training. 105 | #activation = "tanh" # Nonlinearity to use. Default: tanh 106 | ) 107 | #print( "cell :", cell ) 108 | 109 | # 最初の時間 t0 では、過去の隠れ層がないので、 110 | # cell.zero_state(...) でゼロの状態を初期設定する。 111 | initial_state_tsr = cell.zero_state( self._batch_size_holder, tf.float32 ) 112 | #print( "initial_state_tsr :", initial_state_tsr ) 113 | 114 | #----------------------------------------------------------------- 115 | # 過去の隠れ層の再帰処理 116 | #----------------------------------------------------------------- 117 | self._rnn_states.append( initial_state_tsr ) 118 | 119 | with tf.variable_scope('RNN-LSTM'): 120 | for t in range( self._n_in_sequence ): 121 | if (t > 0): 122 | # tf.get_variable_scope() : 名前空間を設定した Variable にアクセス 123 | # reuse_variables() : reuse フラグを True にすることで、再利用できるようになる。 124 | tf.get_variable_scope().reuse_variables() 125 | 126 | # LSTMCellクラスの `__call__(...)` を順次呼び出し、 127 | # 各時刻 t における出力 cell_output, 及び状態 state を算出 128 | cell_output, state_tsr = cell( inputs = self._X_holder[:, t, :], state = self._rnn_states[-1] ) 129 | 130 | # 過去の隠れ層の出力をリストに追加 131 | self._rnn_cells.append( cell_output ) 132 | self._rnn_states.append( state_tsr ) 133 | 134 | # 最終的な隠れ層の出力 135 | output = self._rnn_cells[-1] 136 | 137 | # 隠れ層 ~ 出力層 138 | self._weights.append( self.init_weight_variable( input_shape = [self._n_hiddenLayer, self._n_outputLayer] ) ) 139 | self._biases.append( self.init_bias_variable( input_shape = [self._n_outputLayer] ) ) 140 | 141 | #-------------------------------------------------------------- 142 | # 出力層への入力 143 | #-------------------------------------------------------------- 144 | y_in_op = tf.matmul( output, self._weights[-1] ) + self._biases[-1] 145 | 146 | #-------------------------------------------------------------- 147 | # モデルの出力 148 | #-------------------------------------------------------------- 149 | # 線形活性 150 | self._y_out_op = y_in_op 151 | 152 | return self._y_out_op 153 | -------------------------------------------------------------------------------- /RNN_TensorFlow/NNActivation.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/21] : 新規作成 7 | [17/11/18] : NNActivation クラスの仕様変更。NNActivation クラスの子クラス定義 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNActivation( object ): 19 | """ 20 | ニューラルネットワークの活性化関数を表すクラス 21 | 実際の活性化関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _activate_op : 活性化関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Activation_op" ): 34 | self._activate_op = None 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNActivation" ) 41 | print( self ) 42 | print( str ) 43 | print( "_activate_op :", self._activate_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | def activate( self, input, node_name = "Activation_op" ): 49 | """ 50 | 活性化関数のオペレーターを返す。 51 | 52 | [Input] 53 | input : Operator or placeholder 54 | 活性化関数の入力となる Operatore、又は placeholder 55 | 56 | [Output] 57 | 活性化関数のオペレーター 58 | """ 59 | return self._activate_op 60 | 61 | 62 | class Sigmoid( NNActivation ): 63 | """ 64 | シグモイド関数の活性化関数 65 | NNActivation クラスの子クラスとして定義 66 | """ 67 | def __init__( self, node_name = "Activate_Sigmoid_op" ): 68 | self._activate_op = None 69 | self._node_name = node_name 70 | 71 | return 72 | 73 | def activate( self, input, node_name = "Activate_Sigmoid_op" ): 74 | self._activate_op = tf.nn.sigmoid( input, name = node_name ) 75 | self._node_name = node_name 76 | 77 | return self._activate_op 78 | 79 | 80 | class Relu( NNActivation ): 81 | """ 82 | Relu 関数の活性化関数 83 | NNActivation クラスの子クラスとして定義 84 | """ 85 | def __init__( self, node_name = "Activate_Relu_op" ): 86 | self._activate_op = None 87 | self._node_name = node_name 88 | 89 | return 90 | 91 | def activate( self, input, node_name = "Activate_Relu_op" ): 92 | self._activate_op = tf.nn.relu( input, name = node_name ) 93 | self._node_name = node_name 94 | 95 | return self._activate_op 96 | 97 | 98 | class Softmax( NNActivation ): 99 | """ 100 | softmax 関数の活性化関数 101 | NNActivation クラスの子クラスとして定義 102 | """ 103 | def __init__( self, node_name = "Activate_Softmax_op" ): 104 | self._activate_op = None 105 | self._node_name = node_name 106 | 107 | return 108 | 109 | def activate( self, input, node_name = "Activate_Softmax_op" ): 110 | self._activate_op = tf.nn.softmax( input, name = node_name ) 111 | self._node_name = node_name 112 | 113 | return self._activate_op 114 | 115 | -------------------------------------------------------------------------------- /RNN_TensorFlow/NNLoss.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/xx/xx] : 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | class NNLoss( object ): 18 | """ 19 | ニューラルネットワークの損失関数(評価関数、誤差関数)を表すクラス 20 | 実際の損失関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 21 | ------------------------------------------------------------------------------------------------ 22 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 23 | _loss_op : 損失関数の Operater 24 | _node_name : str 25 | この Operator ノードの名前 26 | 27 | [protedted] protedted な使用法を想定 28 | 29 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 30 | 31 | """ 32 | def __init__( self, node_name = "Loss_op" ): 33 | self._loss_op = loss( t_holder, y_out_op, node_name ) 34 | self._node_name = node_name 35 | 36 | return 37 | 38 | def print( str ): 39 | print( "NNLoss" ) 40 | print( self ) 41 | print( str ) 42 | print( "_loss_op :", self._loss_op ) 43 | print( "_node_name :", self._node_name ) 44 | 45 | return 46 | 47 | 48 | def loss( self, t_holder, y_out_op ): 49 | """ 50 | 損失関数のオペレーターを返す。 51 | 52 | [Input] 53 | _t_holder : Placeholder 54 | 教師データの Placeholder 55 | _y_out_op : Operator 56 | 出力の Operator 57 | 58 | [Output] 59 | 損失関数のオペレーター 60 | """ 61 | self._loss_op = None 62 | 63 | return self._loss_op 64 | 65 | 66 | class L1Norm( NNLoss ): 67 | """ 68 | L1 ノルムの損失関数 69 | NNLoss クラスの子クラスとして定義 70 | """ 71 | def __init__( self, node_name = "Loss_L1Norm_op" ): 72 | self._loss_op = None 73 | self._node_name = node_name 74 | 75 | return 76 | 77 | def loss( self, t_holder, y_out_op, node_name = "Loss_L1Norm_op" ): 78 | # tf.reduce_mean(...) でバッチサイズに対しての平均をとる。 79 | self._loss_op = tf.reduce_mean( 80 | tf.abs( t_holder - y_out_op ) 81 | ) 82 | 83 | return self._loss_op 84 | 85 | 86 | class L2Norm( NNLoss ): 87 | """ 88 | L2 ノルムの損失関数 89 | NNLoss クラスの子クラスとして定義 90 | """ 91 | def __init__( self, node_name = "Loss_L2Norm_op" ): 92 | self._loss_op = None 93 | self._node_name = node_name 94 | 95 | return 96 | 97 | def loss( self, t_holder, y_out_op, node_name = "Loss_L2Norm_op" ): 98 | self._loss_op = tf.reduce_mean( 99 | tf.square( t_holder - y_out_op ) 100 | ) 101 | 102 | return self._loss_op 103 | 104 | 105 | class BinaryCrossEntropy( NNLoss ): 106 | """ 107 | 2値のクロス・エントロピーの損失関数 108 | NNLoss クラスの子クラスとして定義 109 | """ 110 | def __init__( self, node_name = "Loss_BinaryCrossEntropy_op" ): 111 | self._loss_op = None 112 | self._node_name = node_name 113 | 114 | return 115 | 116 | def loss( self, t_holder, y_out_op ): 117 | self._loss_op = -tf.reduce_sum( 118 | t_holder * tf.log( y_out_op ) + ( 1 - t_holder ) * tf.log( 1 - y_out_op ) 119 | ) 120 | 121 | return self._loss_op 122 | 123 | 124 | class CrossEntropy( NNLoss ): 125 | """ 126 | クロス・エントロピーの損失関数 127 | NNLoss クラスの子クラスとして定義 128 | """ 129 | def __init__( self, node_name = "Loss_CrossEntropy_op" ): 130 | self._loss_op = None 131 | self._node_name = node_name 132 | 133 | return 134 | 135 | def loss( self, t_holder, y_out_op, node_name = "Loss_CrossEntropy_op" ): 136 | # softmax で正規化済みの場合 137 | # tf.clip_by_value(...) : 下限値、上限値を設定し, 値が更新されないことを防止 138 | self._loss_op = tf.reduce_mean( # ミニバッチ度に平均値を計算 139 | -tf.reduce_sum( 140 | t_holder * tf.log( tf.clip_by_value(y_out_op, 1e-10, 1.0) ), 141 | reduction_indices = [1] # sum をとる行列の方向 ( 1:row 方向 ) 142 | ) 143 | ) 144 | 145 | return self._loss_op 146 | 147 | 148 | class SoftmaxCrossEntropy( NNLoss ): 149 | """ 150 | ソフトマックス・クロス・エントロピーの損失関数 151 | NNLoss クラスの子クラスとして定義 152 | """ 153 | def __init__( self, node_name = "Loss_SoftmaxCrossEntropy_op" ): 154 | self._loss_op = None 155 | self._node_name = node_name 156 | 157 | return 158 | 159 | def loss( self, t_holder, y_out_op ): 160 | # softmax で正規化済みでない場合 161 | self._loss_op = tf.reduce_mean( 162 | tf.nn.softmax_cross_entropy_with_logits( 163 | labels = t_holder, 164 | logits = y_out_op 165 | ) 166 | ) 167 | 168 | return self._loss_op 169 | 170 | 171 | class SparseSoftmaxCrossEntropy( NNLoss ): 172 | """ 173 | 疎なソフトマックス・クロス・エントロピーの損失関数 174 | NNLoss クラスの子クラスとして定義 175 | """ 176 | def __init__( self, node_name = "Loss_SparseSoftmaxCrossEntropy_op" ): 177 | self._loss_op = None 178 | self._node_name = node_name 179 | 180 | return 181 | 182 | def loss( self, t_holder, y_out_op ): 183 | self._loss_op = tf.reduce_mean( 184 | tf.nn.sparse_softmax_cross_entropy_with_logits( 185 | labels = t_holder, 186 | logits = y_out_op 187 | ) 188 | ) 189 | 190 | return self._loss_op 191 | 192 | 193 | -------------------------------------------------------------------------------- /RNN_TensorFlow/NeuralNetworkBase.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/14] : 新規作成 7 | [17/11/19] : scikit-learn ライブラリの推定器 estimator の基本クラス `BaseEstimator`, `ClassifierMixin` を継承しているように変更 8 | : 各種抽象メソッド追加 9 | [17/12/01] : TensorBoard に計算グラフを表示するためのファイルを書き込むための関数 write_tensorboard_graph(...) 追加 10 | [xx/xx/xx] : 11 | 12 | """ 13 | 14 | from abc import ABCMeta, abstractmethod # 抽象クラスを作成するための ABC クラス 15 | 16 | import numpy 17 | 18 | # scikit-learn ライブラリ関連 19 | from sklearn.base import BaseEstimator # 推定器 Estimator の上位クラス. get_params(), set_params() 関数が定義されている. 20 | from sklearn.base import ClassifierMixin # 推定器 Estimator の上位クラス. score() 関数が定義されている. 21 | 22 | # TensorFlow ライブラリ 23 | import tensorflow as tf 24 | from tensorflow.python.framework import ops 25 | 26 | import NNActivation 27 | from NNActivation import NNActivation # ニューラルネットワークの活性化関数を表すクラス 28 | from NNActivation import Sigmoid 29 | from NNActivation import Relu 30 | from NNActivation import Softmax 31 | 32 | import NNLoss # ニューラルネットワークの損失関数を表すクラス 33 | from NNLoss import L1Norm 34 | from NNLoss import L2Norm 35 | from NNLoss import BinaryCrossEntropy 36 | from NNLoss import CrossEntropy 37 | from NNLoss import SoftmaxCrossEntropy 38 | from NNLoss import SparseSoftmaxCrossEntropy 39 | 40 | import NNOptimizer # ニューラルネットワークの最適化アルゴリズム Optimizer を表すクラス 41 | from NNOptimizer import GradientDecent 42 | from NNOptimizer import Momentum 43 | from NNOptimizer import NesterovMomentum 44 | from NNOptimizer import Adagrad 45 | from NNOptimizer import Adadelta 46 | 47 | 48 | class NeuralNetworkBase( BaseEstimator, ClassifierMixin ): 49 | """ 50 | ニューラルネットワークの基底クラス(自作クラス) 51 | scikit-learn ライブラリの推定器 estimator の基本クラス BaseEstimator, ClassifierMixin を継承している. 52 | TensorFlow ライブラリを使用 53 | ニューラルネットワークの基本的なフレームワークを想定した仮想メソッドからなる抽象クラス。 54 | 実際のニューラルネットワークを表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 55 | 56 | ---------------------------------------------------------------------------------------------------- 57 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 58 | _session : tf.Session() 59 | 自身の Session 60 | _init_var_op : tf.global_variables_initializer() 61 | 全 Variable の初期化オペレーター 62 | 63 | _loss_op : Operator 64 | 損失関数を表すオペレーター 65 | _optimizer : Optimizer 66 | モデルの最適化アルゴリズム 67 | _train_step : 68 | トレーニングステップ 69 | _y_out_op : Operator 70 | モデルの出力のオペレーター 71 | 72 | [protedted] protedted な使用法を想定 73 | 74 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 75 | 76 | """ 77 | 78 | def __init__( self, session = tf.Session() ): 79 | """ 80 | コンストラクタ(厳密にはイニシャライザ) 81 | """ 82 | # メンバ変数の初期化 83 | self._session = session 84 | self._init_var_op = None 85 | 86 | self._loss_op = None 87 | self._optimizer = None 88 | self._train_step = None 89 | self._y_out_op = None 90 | 91 | return 92 | 93 | 94 | def print( self, str ): 95 | print( "NeuralNetworkBase" ) 96 | print( self ) 97 | print( str ) 98 | 99 | print( "_session : \n", self._session ) 100 | print( "_init_var_op : \n", self._init_var_op ) 101 | print( "_loss_op : \n", self._loss_op ) 102 | print( "_y_out_op : \n", self._y_out_op ) 103 | 104 | return 105 | 106 | 107 | @abstractmethod 108 | def model( self ): 109 | """ 110 | モデルの定義を行い、 111 | 最終的なモデルの出力のオペレーター self._y_out_op を設定する。 112 | (抽象メソッド) 113 | 114 | [Output] 115 | self._y_out_op : Operator 116 | モデルの出力のオペレーター 117 | """ 118 | return self._y_out_op 119 | 120 | 121 | @abstractmethod 122 | def loss( self, nnLoss ): 123 | """ 124 | 損失関数(誤差関数、コスト関数)の定義を行う。 125 | (抽象メソッド) 126 | 127 | [Input] 128 | nnLoss : NNLoss クラスのオブジェクト 129 | 130 | [Output] 131 | self._loss_op : Operator 132 | 損失関数を表すオペレーター 133 | """ 134 | return self._loss_op 135 | 136 | 137 | @abstractmethod 138 | def optimizer( self, nnOptimizer ): 139 | """ 140 | モデルの最適化アルゴリズムの設定を行う。(抽象メソッド) 141 | 142 | [Input] 143 | nnOptimizer : NNOptimizer のクラスのオブジェクト 144 | 145 | [Output] 146 | optimizer の train_step 147 | 148 | """ 149 | return self._train_step 150 | 151 | 152 | @abstractmethod 153 | def fit( self, X_train, y_train ): 154 | """ 155 | 指定されたトレーニングデータで、モデルの fitting 処理を行う。(抽象メソッド) 156 | 157 | [Input] 158 | X_train : numpy.ndarray ( shape = [n_samples, n_features] ) 159 | トレーニングデータ(特徴行列) 160 | 161 | y_train : numpy.ndarray ( shape = [n_samples] ) 162 | レーニングデータ用のクラスラベル(教師データ)のリスト 163 | 164 | [Output] 165 | self : 自身のオブジェクト 166 | """ 167 | return self 168 | 169 | 170 | @abstractmethod 171 | def predict( self, X_features ): 172 | """ 173 | fitting 処理したモデルで、推定を行い、予想値を返す。(抽象メソッド) 174 | 175 | [Input] 176 | X_features : numpy.ndarry ( shape = [n_samples, n_features] ) 177 | 予想したい特徴行列 178 | 179 | [Output] 180 | results : numpy.ndaary ( shape = [n_samples] ) 181 | 予想結果(分類モデルの場合は、クラスラベル) 182 | """ 183 | return 184 | 185 | 186 | @abstractmethod 187 | def predict_proba( self, X_test ): 188 | """ 189 | fitting 処理したモデルで、推定を行い、クラスの所属確率の予想値を返す。(抽象メソッド) 190 | proba : probability 191 | 192 | [Input] 193 | X_test : numpy.ndarry ( shape = [n_samples, n_features] ) 194 | 予想したい特徴行列 195 | """ 196 | return 197 | 198 | @abstractmethod 199 | def accuracy( self, X_test, y_test ): 200 | """ 201 | 指定したデータでの正解率 [accuracy] を計算する。 202 | """ 203 | return 204 | 205 | @abstractmethod 206 | def accuracy_labels( self, X_test, y_test ): 207 | """ 208 | 指定したデータでのラベル毎の正解率 [acuuracy] を算出する。 209 | """ 210 | return 211 | 212 | 213 | def write_tensorboard_graph( self, dir = "./TensorBoard" ): 214 | """ 215 | TensorBoard に計算グラフを表示するためのファイルを書き込む。 216 | [Input] 217 | dir : str 218 | TensorBoard 用のファイルを作成するディレクトリのパス 219 | """ 220 | # TensorBoard 用のファイル(フォルダ)を作成 221 | merged = tf.summary.merge_all() # Add summaries to tensorboard 222 | summary_writer = tf.summary.FileWriter( dir, graph = self._session.graph ) # tensorboard --logdir=${PWD} 223 | 224 | return -------------------------------------------------------------------------------- /Seq2Seq_RNN_Encoder-Decoder_TensorFlow/NNActivation.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/10/21] : 新規作成 7 | [17/11/18] : NNActivation クラスの仕様変更。NNActivation クラスの子クラス定義 8 | : 9 | """ 10 | 11 | import numpy 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | 18 | class NNActivation( object ): 19 | """ 20 | ニューラルネットワークの活性化関数を表すクラス 21 | 実際の活性化関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _activate_op : 活性化関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Activation_op" ): 34 | self._activate_op = None 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNActivation" ) 41 | print( self ) 42 | print( str ) 43 | print( "_activate_op :", self._activate_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | def activate( self, input, node_name = "Activation_op" ): 49 | """ 50 | 活性化関数のオペレーターを返す。 51 | 52 | [Input] 53 | input : Operator or placeholder 54 | 活性化関数の入力となる Operatore、又は placeholder 55 | 56 | [Output] 57 | 活性化関数のオペレーター 58 | """ 59 | return self._activate_op 60 | 61 | 62 | class Sigmoid( NNActivation ): 63 | """ 64 | シグモイド関数の活性化関数 65 | NNActivation クラスの子クラスとして定義 66 | """ 67 | def __init__( self, node_name = "Activate_Sigmoid_op" ): 68 | self._activate_op = None 69 | self._node_name = node_name 70 | 71 | return 72 | 73 | def activate( self, input, node_name = "Activate_Sigmoid_op" ): 74 | self._activate_op = tf.nn.sigmoid( input, name = node_name ) 75 | self._node_name = node_name 76 | 77 | return self._activate_op 78 | 79 | 80 | class Relu( NNActivation ): 81 | """ 82 | Relu 関数の活性化関数 83 | NNActivation クラスの子クラスとして定義 84 | """ 85 | def __init__( self, node_name = "Activate_Relu_op" ): 86 | self._activate_op = None 87 | self._node_name = node_name 88 | 89 | return 90 | 91 | def activate( self, input, node_name = "Activate_Relu_op" ): 92 | self._activate_op = tf.nn.relu( input, name = node_name ) 93 | self._node_name = node_name 94 | 95 | return self._activate_op 96 | 97 | 98 | class Softmax( NNActivation ): 99 | """ 100 | softmax 関数の活性化関数 101 | NNActivation クラスの子クラスとして定義 102 | """ 103 | def __init__( self, node_name = "Activate_Softmax_op" ): 104 | self._activate_op = None 105 | self._node_name = node_name 106 | 107 | return 108 | 109 | def activate( self, input, node_name = "Activate_Softmax_op" ): 110 | self._activate_op = tf.nn.softmax( input, name = node_name ) 111 | self._node_name = node_name 112 | 113 | return self._activate_op 114 | 115 | -------------------------------------------------------------------------------- /Seq2Seq_RNN_Encoder-Decoder_TensorFlow/NNLoss.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 4.3.0 環境 (TensorFlow インストール済み) 3 | 4 | """ 5 | 更新情報 6 | [17/11/18] : 新規作成 7 | [17/12/04] : 損失関数の処理の名前空間を設定するように修正 8 | [17/xx/xx] : 9 | : 10 | """ 11 | 12 | import numpy 13 | 14 | # TensorFlow ライブラリ 15 | import tensorflow as tf 16 | from tensorflow.python.framework import ops 17 | 18 | class NNLoss( object ): 19 | """ 20 | ニューラルネットワークの損失関数(評価関数、誤差関数)を表すクラス 21 | 実際の損失関数を表すクラスの実装は、このクラスを継承し、オーバーライドするを想定している。 22 | ------------------------------------------------------------------------------------------------ 23 | [public] public アクセス可能なインスタスンス変数には, 便宜上変数名の最後にアンダースコア _ を付ける. 24 | _loss_op : 損失関数の Operater 25 | _node_name : str 26 | この Operator ノードの名前 27 | 28 | [protedted] protedted な使用法を想定 29 | 30 | [private] 変数名の前にダブルアンダースコア __ を付ける(Pythonルール) 31 | 32 | """ 33 | def __init__( self, node_name = "Loss_op" ): 34 | self._loss_op = loss( t_holder, y_out_op, node_name ) 35 | self._node_name = node_name 36 | 37 | return 38 | 39 | def print( str ): 40 | print( "NNLoss" ) 41 | print( self ) 42 | print( str ) 43 | print( "_loss_op :", self._loss_op ) 44 | print( "_node_name :", self._node_name ) 45 | 46 | return 47 | 48 | 49 | def loss( self, t_holder, y_out_op ): 50 | """ 51 | 損失関数のオペレーターを返す。 52 | 53 | [Input] 54 | _t_holder : Placeholder 55 | 教師データの Placeholder 56 | _y_out_op : Operator 57 | 出力の Operator 58 | 59 | [Output] 60 | 損失関数のオペレーター 61 | """ 62 | # 名前空間の範囲 63 | with tf.name_scope( self._node_name ): 64 | self._loss_op = None 65 | 66 | return self._loss_op 67 | 68 | 69 | class L1Norm( NNLoss ): 70 | """ 71 | L1 ノルムの損失関数 72 | NNLoss クラスの子クラスとして定義 73 | """ 74 | def __init__( self, node_name = "Loss_L1Norm_op" ): 75 | self._loss_op = None 76 | self._node_name = node_name 77 | 78 | return 79 | 80 | def loss( self, t_holder, y_out_op, node_name = "Loss_L1Norm_op" ): 81 | with tf.name_scope( self._node_name ): 82 | # tf.reduce_mean(...) でバッチサイズに対しての平均をとる。 83 | self._loss_op = tf.reduce_mean( 84 | tf.abs( t_holder - y_out_op ) 85 | ) 86 | 87 | return self._loss_op 88 | 89 | 90 | class L2Norm( NNLoss ): 91 | """ 92 | L2 ノルムの損失関数 93 | NNLoss クラスの子クラスとして定義 94 | """ 95 | def __init__( self, node_name = "Loss_L2Norm_op" ): 96 | self._loss_op = None 97 | self._node_name = node_name 98 | 99 | return 100 | 101 | def loss( self, t_holder, y_out_op, node_name = "Loss_L2Norm_op" ): 102 | with tf.name_scope( self._node_name ): 103 | self._loss_op = tf.reduce_mean( 104 | tf.square( t_holder - y_out_op ) 105 | ) 106 | 107 | return self._loss_op 108 | 109 | 110 | class BinaryCrossEntropy( NNLoss ): 111 | """ 112 | 2値のクロス・エントロピーの損失関数 113 | NNLoss クラスの子クラスとして定義 114 | """ 115 | def __init__( self, node_name = "Loss_BinaryCrossEntropy_op" ): 116 | self._loss_op = None 117 | self._node_name = node_name 118 | 119 | return 120 | 121 | def loss( self, t_holder, y_out_op ): 122 | with tf.name_scope( self._node_name ): 123 | self._loss_op = -tf.reduce_sum( 124 | t_holder * tf.log( y_out_op ) + ( 1 - t_holder ) * tf.log( 1 - y_out_op ) 125 | ) 126 | 127 | return self._loss_op 128 | 129 | 130 | class CrossEntropy( NNLoss ): 131 | """ 132 | クロス・エントロピーの損失関数 133 | NNLoss クラスの子クラスとして定義 134 | """ 135 | def __init__( self, node_name = "Loss_CrossEntropy_op" ): 136 | self._loss_op = None 137 | self._node_name = node_name 138 | 139 | return 140 | 141 | def loss( self, t_holder, y_out_op, node_name = "Loss_CrossEntropy_op" ): 142 | with tf.name_scope( self._node_name ): 143 | # softmax で正規化済みの場合 144 | # tf.clip_by_value(...) : 下限値、上限値を設定し, 値が更新されないことを防止 145 | self._loss_op = tf.reduce_mean( # ミニバッチ度に平均値を計算 146 | -tf.reduce_sum( 147 | t_holder * tf.log( tf.clip_by_value(y_out_op, 1e-10, 1.0) ), 148 | reduction_indices = [1] # sum をとる行列の方向 ( 1:row 方向 ) 149 | ) 150 | ) 151 | 152 | return self._loss_op 153 | 154 | 155 | class SoftmaxCrossEntropy( NNLoss ): 156 | """ 157 | ソフトマックス・クロス・エントロピーの損失関数 158 | NNLoss クラスの子クラスとして定義 159 | """ 160 | def __init__( self, node_name = "Loss_SoftmaxCrossEntropy_op" ): 161 | self._loss_op = None 162 | self._node_name = node_name 163 | 164 | return 165 | 166 | def loss( self, t_holder, y_out_op ): 167 | with tf.name_scope( self._node_name ): 168 | # softmax で正規化済みでない場合 169 | self._loss_op = tf.reduce_mean( 170 | tf.nn.softmax_cross_entropy_with_logits( 171 | labels = t_holder, 172 | logits = y_out_op 173 | ) 174 | ) 175 | 176 | return self._loss_op 177 | 178 | 179 | class SparseSoftmaxCrossEntropy( NNLoss ): 180 | """ 181 | 疎なソフトマックス・クロス・エントロピーの損失関数 182 | NNLoss クラスの子クラスとして定義 183 | """ 184 | def __init__( self, node_name = "Loss_SparseSoftmaxCrossEntropy_op" ): 185 | self._loss_op = None 186 | self._node_name = node_name 187 | 188 | return 189 | 190 | def loss( self, t_holder, y_out_op ): 191 | with tf.name_scope( self._node_name ): 192 | self._loss_op = tf.reduce_mean( 193 | tf.nn.sparse_softmax_cross_entropy_with_logits( 194 | labels = t_holder, 195 | logits = y_out_op 196 | ) 197 | ) 198 | 199 | return self._loss_op 200 | 201 | 202 | -------------------------------------------------------------------------------- /Seq2Seq_RNN_Encoder-Decoder_TensorFlow/_Old/main2.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # Anaconda 5.0.1 環境 (TensorFlow インストール済み) 3 | # 4 | # conda create -n tensorflow python=3.5 5 | # activate tensorflow 6 | # pip install --ignore-installed --upgrade tensorflow 7 | # pip install --ignore-installed --upgrade tensorflow-gpu 8 | 9 | import numpy 10 | import pandas 11 | import matplotlib.pyplot as plt 12 | 13 | # TensorFlow ライブラリ 14 | import tensorflow as tf 15 | from tensorflow.python.framework import ops 16 | 17 | # 自作クラス 18 | from MLPreProcess import MLPreProcess 19 | from MLPlot import MLPlot 20 | 21 | import NNActivation # ニューラルネットワークの活性化関数を表すクラス 22 | from NNActivation import NNActivation 23 | from NNActivation import Sigmoid 24 | from NNActivation import Relu 25 | from NNActivation import Softmax 26 | 27 | import NNLoss # ニューラルネットワークの損失関数を表すクラス 28 | from NNLoss import L1Norm 29 | from NNLoss import L2Norm 30 | from NNLoss import BinaryCrossEntropy 31 | from NNLoss import CrossEntropy 32 | from NNLoss import SoftmaxCrossEntropy 33 | from NNLoss import SparseSoftmaxCrossEntropy 34 | 35 | import NNOptimizer # ニューラルネットワークの最適化アルゴリズム Optimizer を表すクラス 36 | from NNOptimizer import GradientDecent 37 | from NNOptimizer import GradientDecentDecay 38 | from NNOptimizer import Momentum 39 | from NNOptimizer import NesterovMomentum 40 | from NNOptimizer import Adagrad 41 | from NNOptimizer import Adadelta 42 | from NNOptimizer import Adam 43 | 44 | from NeuralNetworkBase import NeuralNetworkBase 45 | from RecurrectNNEncoderDecoderLSTM import RecurrectNNEncoderDecoderLSTM 46 | from Seq2SeqRNNEncoderDecoderLSTM import Seq2SeqRNNEncoderDecoderLSTM 47 | 48 | 49 | def main(): 50 | """ 51 | TensorFlow を用いた RNN Encoder-Decoder(LSTM 使用) によるシェイクスピア作品のワード予想処理 52 | """ 53 | print("Enter main()") 54 | 55 | # Reset graph 56 | #ops.reset_default_graph() 57 | 58 | #====================================================================== 59 | # データセットを読み込み or 生成 60 | # Import or generate data. 61 | #====================================================================== 62 | path_text = "C:\Data\MachineLearning_DataSet\Project_Gutenberg\William_Shakespeare\pg100.txt" 63 | 64 | # The Project Gutenberg EBook にある、シェイクスピア作品のテキストデータの読み込み&抽出処理 65 | text_data = MLPreProcess.load_textdata_by_shakespeare_from_theProjectGutenbergEBook( path = path_text, n_DeleteParagraph = 182, bCleaning = True ) 66 | #print( "text_data :\n", text_data ) 67 | 68 | # 抽出したテキストデータから、出現頻度の高い単語をディクショナリに登録する 69 | # 抽出したテキストデータを、このディクショナリに基づき、数値インデックス情報に変換する。 70 | text_data_idx, n_vocab = MLPreProcess.text_vocabulary_processing_without_tensorflow( text_data , min_word_freq = 5 ) 71 | print( "text_data_idx :", text_data_idx ) 72 | print( "len( text_data_idx ) :", len( text_data_idx ) ) 73 | print( "n_vocab :", n_vocab ) 74 | 75 | #====================================================================== 76 | # データを変換、正規化 77 | # Transform and normalize data. 78 | # ex) data = tf.nn.batch_norm_with_global_normalization(...) 79 | #====================================================================== 80 | 81 | 82 | #====================================================================== 83 | # データセットをトレーニングデータ、テストデータ、検証データセットに分割 84 | #====================================================================== 85 | 86 | 87 | #====================================================================== 88 | # アルゴリズム(モデル)のパラメータを設定 89 | # Set algorithm parameters. 90 | # ex) learning_rate = 0.01 iterations = 1000 91 | #====================================================================== 92 | learning_rate1 = 0.001 93 | adam_beta1 = 0.9 # For the Adam optimizer 94 | adam_beta2 = 0.999 # For the Adam optimizer 95 | 96 | rnn1 = Seq2SeqRNNEncoderDecoderLSTM( 97 | session = tf.Session(), 98 | n_inputLayer = 1, 99 | n_hiddenLayer = 128, # 1つの LSTM ブロック中に集約されている隠れ層のノード数 100 | n_outputLayer = 1, 101 | n_in_sequence_encoder = 50, # エンコーダー側のシーケンス長 / 102 | n_in_sequence_decoder = 50, # デコーダー側のシーケンス長 / 103 | n_vocab = n_vocab, # 7511 104 | epochs = 1000, 105 | batch_size = 100, 106 | eval_step = 1, 107 | save_step = 500 108 | ) 109 | rnn1.print( "after __init__()" ) 110 | 111 | #====================================================================== 112 | # 変数とプレースホルダを設定 113 | # Initialize variables and placeholders. 114 | # TensorFlow は, 損失関数を最小化するための最適化において, 115 | # 変数と重みベクトルを変更 or 調整する。 116 | # この変更や調整を実現するためには, 117 | # "プレースホルダ [placeholder]" を通じてデータを供給(フィード)する必要がある。 118 | # そして, これらの変数とプレースホルダと型について初期化する必要がある。 119 | # ex) a_tsr = tf.constant(42) 120 | # x_input_holder = tf.placeholder(tf.float32, [None, input_size]) 121 | # y_input_holder = tf.placeholder(tf.fload32, [None, num_classes]) 122 | #====================================================================== 123 | 124 | 125 | #====================================================================== 126 | # モデルの構造を定義する。 127 | # Define the model structure. 128 | # ex) add_op = tf.add(tf.mul(x_input_holder, weight_matrix), b_matrix) 129 | #====================================================================== 130 | rnn1.model() 131 | rnn1.print( "after model()" ) 132 | 133 | #====================================================================== 134 | # 損失関数を設定する。 135 | # Declare the loss functions. 136 | #====================================================================== 137 | rnn1.loss( L2Norm() ) 138 | 139 | #====================================================================== 140 | # モデルの最適化アルゴリズム Optimizer を設定する。 141 | # Declare Optimizer. 142 | #====================================================================== 143 | #rnn1.optimizer( Adam( learning_rate = learning_rate1, beta1 = adam_beta1, beta2 = adam_beta2 ) ) 144 | 145 | #====================================================================== 146 | # モデルの初期化と学習(トレーニング) 147 | # ここまでの準備で, 実際に, 計算グラフ(有向グラフ)のオブジェクトを作成し, 148 | # プレースホルダを通じて, データを計算グラフ(有向グラフ)に供給する。 149 | # Initialize and train the model. 150 | # 151 | # ex) 計算グラフを初期化する方法の1つの例 152 | # with tf.Session( graph = graph ) as session: 153 | # ... 154 | # session.run(...) 155 | # ... 156 | # session = tf.Session( graph = graph ) 157 | # session.run(…) 158 | #====================================================================== 159 | # TensorBoard 用のファイル(フォルダ)を作成 160 | #rnn1.write_tensorboard_graph() 161 | 162 | # fitting 処理を行う 163 | #rnn1.fit( X_train, y_train ) 164 | #rnn1.print( "after fitting" ) 165 | 166 | #====================================================================== 167 | # モデルの評価 168 | # (Optional) Evaluate the model. 169 | #====================================================================== 170 | #--------------------------------------------------------- 171 | # 損失関数を plot 172 | #--------------------------------------------------------- 173 | """ 174 | plt.clf() 175 | plt.plot( 176 | range( rnn1._epochs ), rnn1._losses_train, 177 | label = 'RNN - %s = [%d - %d - %d], learning_rate = %0.3f' % ( type(rnn1) , rnn1._n_inputLayer, rnn1._n_hiddenLayer, rnn1._n_outputLayer, learning_rate1 ) , 178 | linestyle = '-', 179 | linewidth = 0.2, 180 | color = 'red' 181 | ) 182 | plt.title( "loss / L2 Norm (MSE)" ) 183 | plt.legend( loc = 'best' ) 184 | plt.ylim( ymin = 0.0 ) 185 | plt.xlabel( "Epocs" ) 186 | plt.grid() 187 | plt.tight_layout() 188 | 189 | MLPlot.saveFigure( fileName = "RNN-LSTM_3-1.png" ) 190 | plt.show() 191 | """ 192 | #--------------------------------------------------------- 193 | # 予想値 194 | #--------------------------------------------------------- 195 | # 予想値を取得 196 | #predicts1 = rnn1.predict( X_features ) 197 | #print( "predicts1 :\n", predicts1 ) 198 | 199 | 200 | #====================================================================== 201 | # ハイパーパラメータのチューニング (Optional) 202 | #====================================================================== 203 | 204 | 205 | #====================================================================== 206 | # デプロイと新しい成果指標の予想 (Optional) 207 | #====================================================================== 208 | 209 | 210 | print("Finish main()") 211 | return 212 | 213 | 214 | if __name__ == '__main__': 215 | main() 216 | -------------------------------------------------------------------------------- /dataset.md: -------------------------------------------------------------------------------- 1 | ## 検証用データセット 2 | 3 | ### Iris データセット : (csvフォーマット) 4 | URL : https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data 5 | 6 | 全サンプル数 150 個の内、アヤメの品種("setosa", "versicolor", "versicolor" )は、以下のように構成されている。
50 | 51 | ### ワインデータセット:(csvフォーマット) 52 | 53 | URL : https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data
54 | 55 | コラムにラベルを追加して記載した表 56 | 57 | ||Class label |Alcohol |Malic acid |Ash |Alcalinity of ash|Magnesium |Total phenols|Flavanoids|Nonflavanoid phenols|Proanthocyanins|Color intensity|Hue|OD280/OD315 of diluted wines|Proline| 58 | |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| 59 | |0 |1 |14.23 |1.71 |2.43 |15.6 |127 |2.80|3.06|0.28|2.29|5.640000|1.04|3.92|1065| 60 | |1 |1 |13.20 |1.78 |2.14 |11.2 |100 |2.65|2.76|0.26|1.28|4.380000|1.05|3.40|1050| 61 | |2 |1 |13.16 |2.36 |2.67 |18.6 |101 |2.80|3.24|0.30|2.81|5.680000|1.03|3.17|1185| 62 | |3 |1 |14.37 |1.95 |2.50 |16.8 |113 |3.85|3.49|0.24|2.18|7.800000|0.86|3.45|1480| 63 | |4 |1 |13.24 |2.59 |2.87 |21.0 |118 |2.80|2.69|0.39|1.82|4.320000|1.04|2.93|735| 64 | |5 |1 |14.20 |1.76 |2.45 |15.2 |112 |3.27|3.39|0.34|1.97|6.750000|1.05|2.85|1450| 65 | |...|...|...|...|...|...|...|...|...|...|...|...|...|...|...| 66 | |170|3|12.20|3.03|2.32|19.0|96 |1.25|0.49|0.40|0.73|5.500000 |0.66|1.83|510| 67 | |171|3|12.77|2.39|2.28|19.5|86 |1.39|0.51|0.48|0.64|9.899999 |0.57|1.63|470| 68 | |172|3|14.16|2.51|2.48|20.0|91 |1.68|0.70|0.44|1.24|9.700000 |0.62|1.71|660| 69 | |173|3|13.71|5.65|2.45|20.5|95 |1.68|0.61|0.52|1.06|7.700000 |0.64|1.74|740| 70 | |174|3|13.40|3.91|2.48|23.0|102|1.80|0.75|0.43|1.41|7.300000 |0.70|1.56|750| 71 | |175|3|13.27|4.28|2.26|20.0|120|1.59|0.69|0.43|1.35|10.200000 |0.59|1.56|835| 72 | |176|3|13.17|2.59|2.37|20.0|120|1.65|0.68|0.53|1.46|9.300000 |0.60|1.62|840| 73 | |177|3|14.13|4.10|2.74|24.5|96 |2.05|0.76|0.56|1.35|9.200000 |0.61|1.60|560| 74 | 75 |
76 | 77 | ### Brest Cancer Wisconsin データセット:(csvフォーマット) 78 | 79 | URL : https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data 80 | 81 | 悪性腫瘍細胞と良性腫瘍細胞の 569 個のサンプルが含まれている。
1 列目は固有の ID 、2 列目は悪性 [malignant] or 良性 [belign] を表すラベル、3 ~ 32 列目には、細胞核のデジタル画像から算出された 30 個の実数値の特徴量が含まれれいる。 82 | 83 | |行番号|ID|悪性(M)/良性(B)|1|2|3|4|5|6|7|8|...|22|23|24|25|26|27|28|29|30| 84 | |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| 85 | |1|842302 |M |17.990 |10.38 |122.80 |1001.0 |0.11840 |0.27760 |0.300100|0.147100|...|25.380|17.33| 184.60 |2019.0 |0.16220| 0.66560| 0.71190| 0.26540| 0.4601| 0.11890 | 86 | |2|842517 |M |20.570 |17.77 |132.90 |1326.0 |0.08474 |0.07864 |0.086900|0.147100|...|25.380| 17.33 |184.60 |2019.0 |0.16220 |0.66560|0.24160 |0.18600 |0.2750 |0.08902| 87 | |3|84300903 |M |19.690 |21.25 |130.00 |1203.0 |0.10960 |0.15990 |0.197400|0.127900 |...|23.570 |25.53 |152.50 |1709.0 |0.14440 |0.42450|0.45040 |0.24300 |0.3613 |0.08758| 88 | |...| 89 | |568|927241 |M |20.600 |29.33 |140.10 |1265.0 |0.11780 |0.27700 |0.351400|0.152000 |...|25.740 |39.42 |184.60 |1821.0 |0.16500 |0.86810|0.93870 |0.26500 |0.4087 |0.12400| 90 | |569|92751 |B |7.760 |24.54 |47.92 |181.0 |0.05263 |0.04362 |0.000000|0.000000|...|9.456 |30.37 |59.16 |268.6 |0.08996 |0.06444|0.00000 |0.00000 |0.2871 |0.07039| 91 | 92 |
93 | 94 | ### 渦巻きデータ:(csvフォーマット) 95 | 96 | URL : https://github.com/Yagami360/MachineLearning_Exercises_Python_scikit-learn/blob/master/EnsembleLearning_scikit-learn/data/naruto.csv 97 | 98 | 2クラス(0 or 1)識別問題用の渦巻状のデータ。 99 | 100 |
101 | 102 | ### MNIST:(手書き数字文字画像データ) 103 | 104 | URL : http://yann.lecun.com/exdb/mnist/ 105 | 106 | - トレーニング用データセットの画像 107 | - `train-images.idx3-ubyte` : 60,000 サンプル、解凍後 47 MB 108 | - トレーニング用データセットのラベル(教師データ) 109 | - `train-labels.idx1-ubyte` : 60,000 サンプル、解凍後 60 KB 110 | - テスト用データセットの画像 111 | - `t10k-images.idx3-ubyte` : 10,000 サンプル、解凍後 7.8 MB 112 | - テストデータセットのラベル(教師データ) 113 | - `t10k-labels.idx1-ubyte` : 10,000 サンプル、解凍後 10 KB 114 | 115 | トレーニングデータセットは、250 人の手書き数字で構成されている。(内訳は、高校生と国税調査員が半数ずつ)
116 | テストデータセットには、同じ割合(高校生と国税調査員が半数ずつ)で、別の人々の手書き数字が含まれている。 117 | 118 | - 各画像は、28 × 28 pixel で構成されている。 119 | - 1次元配列に変換すると、784 個の特徴数になる。 120 | - クラスラベルは、0 ~ 9 の数字から成る。 121 | - 画像データは、バイトフォーマットで保管されており、ビッグエンディアン方式で格納 122 | 123 | 以下、データセットのフォーマットの詳細 124 | 125 | |アドレスのオフセット|型|値|意味| 126 | |---|---|---|---| 127 | |0x0000|32 bit整数|0x0000 0801 (2049)|ファイル種類識別用のマジックナンバー| 128 | |0x0004|32 bit整数|0x0000 EA60 (60000)|サンプル数| 129 | |0x0008|符号なし byte|...|ラベル値| 130 | |0x0009|符号なし byte|...|ラベル値| 131 | |0x000A|符号なし byte|...|ラベル値| 132 | |...|...|...|...| 133 | |0x????|符号なし byte|...|ラベル値| 134 | 135 | - 0 ~ 9 のラベルとなる先頭の画像 9 枚 136 | 137 | ![multilayerperceptron_3-1](https://user-images.githubusercontent.com/25688193/32138999-e4aa485a-bc78-11e7-97f4-b3f358f3f752.png) 138 | 139 | - 7 のラベルとなる先頭の画像 25 枚 140 | 141 | ![multilayerperceptron_3-2](https://user-images.githubusercontent.com/25688193/32139064-8594a6ce-bc7a-11e7-8081-309c14485b9d.png) 142 | 143 | 参考URL : https://qiita.com/mine820/items/e9c08439465a5580a9cb 144 | 145 |
146 | 147 | ### CIFAR-10 データセット 148 | 149 | URL : https://www.cs.toronto.edu/~kriz/cifar.html 150 | 151 | - 10 個のクラスからなる 32×32 pixcel の画像 60,000 個から構成されるデータセット 152 | - これら 10 個のクラスは、それぞれ、
153 | 1 : 飛行機、2 : 自動車、3 : 鳥、4 : ネコ、5 : イヌ、6 : カエル、7 : 馬、8 : 船、9 : トラック 154 | を表している。 155 | - 各画像は、RGB の 3 チャンネルのカラー画像。(※MNISTデータセットは、グレースケールの1チェンネルであった) 156 | - 50000枚(各クラス5000枚)の訓練画像と10000枚(各クラス1000枚)のテスト画像に分割されている 157 | - バイナリー用のファイルは、CIFAR-10 binary version (suitable for C programs) 158 | - Python用のファイル `cifar-10-python.tar.gz` の内容は、cPickle 形式 159 | 160 | 以下、各ファイルのフォーマットの詳細 161 | 162 | |レコード数|ラベル値|R 値|G 値|B 値| 163 | |---|---|---|---|---| 164 | |レコード 1|1 byte|1024 byte|1024 byte|1024 byte| 165 | |レコード 2|1 byte|1024 byte|1024 byte|1024 byte| 166 | |...|...|...|...|...| 167 | |レコード 10,000|1 byte|1024 byte|1024 byte|1024 byte| 168 | 169 | レコードは固定長の3,073バイト。先頭の1バイトがラベルで、残り3,072バイトは縦横32pxの画像データを直列化したものになっており、一般的なBitmap形式と違い、RGB各チャンネルのデータが1,024バイトずつ並ぶ構造になっている。
そして、これらのファイルが data_batch_1, data_batch_2, data_batch_3, data_batch_4, data_batch_5, test_batch の 6つのファイル、合計 60,000 サンプル存在する。 170 | 171 | - 先頭の画像 64 枚
172 | ![cnn_2-1-2](https://user-images.githubusercontent.com/25688193/33030307-55cc89a2-ce5e-11e7-88c8-59675684d9e0.png) 173 | 174 | - 7 : 馬のラベルとなる先頭の画像 64 枚
175 | ![cnn_2-2-2 _label7](https://user-images.githubusercontent.com/25688193/33030404-92b147a4-ce5e-11e7-8b2d-fe65b8dc35bc.png) 176 | 177 | 参考URL : http://aidiary.hatenablog.com/entry/20151014/1444827123 --------------------------------------------------------------------------------