Upload
yuji-kawakami
View
216
Download
7
Embed Size (px)
Citation preview
Karabiner.inc
葉物野菜見極めたい!
By Keras
Karabiner.inc
今日の内容は単純な画像分類です!
詳しい方には退屈かも・・
Karabiner.inc
画像分類について
• 画像から特徴を抽出し、どんな画像か判断すること
入力データ
機械学習 トナカイっぽいけど犬!
Karabiner.inc
Kerasって?
Karabiner.inc
KerasTesorFlowと Theanoのための深層学習ライブラリー
TesorFlow( or Theano)の機能を使いながら、直感的にニューラルネットワークの構築ができる!今回バックグランドに TensorFlowを使いました。
https://keras.io/ja/
Karabiner.inc
TensorFlow• Google社が提供する機械学習ライブラリー
https://www.tensorflow.org/
Karabiner.inc
Kerasで簡単にできること① ニューラルネットワークのモデル構築 &学習② 学習済みモデルを使う③ Fine-tuningを行える④ 実装ラクチンな便利機能( callback)
Karabiner.inc
from keras.models import Sequentialfrom keras.layers import Dense, Activationmodel = Sequential()model.add(Dense(output_dim=3, input_dim=4)) model.add(Activation("relu")) model.add(Dense(output_dim=3)) model.add(Activation("softmax"))
Python
①ニューラルネットワークモデルの構築
例)全結合層のニューラルネットワークモデル4次元の入力値を3次元出力(活性化関数:ReLu)3次元の入力値を3次元出力(活性化関数:softmax)
最初に入力サイズを入れたら後は不要
Karabiner.inc
# 学習の仕方を指定(単純バージョン)model.compile(loss='mean_squared_error', optimizer='sgd')
# 学習の仕方を指定(詳細バージョン)sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mean_squared_error', optimizer=sgd)
# 学習の開始model.fit(data, labels, nb_epoch=10, batch_size=32)
Python
①ニューラルネットワークモデルの学習
例)学習方法を SGDに指定する場合
【 SGDのパラメータ】• lr: float >= 0. 学習率.• momentum: float >= 0. モーメンタム.• decay: float >= 0. 各更新の学習率減衰.• nesterov: boolean. Nesterov momentumを適用するかどうか.
Karabiner.inc
from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictionsfrom keras.preprocessing import imageimport numpy as np
model = VGG16(weights=‘imagenet’) # モデルの読み込み# 入力画像のロードimg = image.load_img("./sample.jpg", target_size=(224, 224)) x = image.img_to_array(img) # 入力画像の行列化x = np.expand_dims(x, axis=0) # 4次元テンソル# 予測preds = model.predict(preprocess_input(x))results = decode_predictions(preds, top=5)[0]# 結果出力for result in results: print(result)
Python
②学習済みモデルを使う例) ImageNetを学習した VGG16を使う場合
Karabiner.inc
③Fine-tuningを行える
畳み込みニューラルネットワークは出力層に近づけば近づくほど、より細かい特徴を捉えた状態のため、その部分ところだけ学習させ、上層部分は学習させない(フリーズ)画像引用: http://cs231n.stanford.edu/slides/winter1516_lecture11.pdf
Karabiner.inc
input_tensor = Input(shape=(img_size[0],img_size[1],3))vgg16_model = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)top_model = Sequential() top_model.add(Flatten(input_shape=vgg16_model.output_shape[1:]))top_model.add(Dense(256, activation='relu'))top_model.add(Dropout(0.5))top_model.add(Dense(3, activation='sigmoid'))model = Model(input=vgg16_model.input, output=top_model(vgg16_model.output))# 学習させないところをフリーズさせるfor layer in model.layers[:15]: layer.trainable = False
Python
③Fine-tuningを行える例) ImageNetを学習した VGG16を使う場合
記述量少なめで Fine-tuningを試すことができる。参考: https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html
Karabiner.inc
# callbackの定義cp_cb = ModelCheckpoint(filepath=‘filename.hdf5', monitor='val_loss', verbose=0, save_best_only=False, mode='auto') tb_cb = TensorBoard(log_dir='logs', histogram_freq=0, write_graph=True)
model.fit(X_train, Y_train, callbacks=[cp_cb, tb_cb])
Python
③実装ラクチンな便利機能例)チェックポイントと Tensorboardを使う場合
他にも Callbackに便利な機能あり。ドキュメント参照: https://keras.io/ja/callbacks/
Karabiner.inc
今回やってみたいこと→葉物野菜の分類
誰得?
Karabiner.inc
葉物野菜の分類
キャベツ レタスはくさい
はくさいはまだしも、キャベツとレタス間違う人はいるかもよ?→Kerasで画像分類モデルを作って解決!
Karabiner.inc
とりあえずやってみる
Jupyter Notebookで実践
Karabiner.inc
TensorFlow実装Python
name filter stride paddingoutput
map size function
data - - - 227×227×3 -conv1 11×11 4 - 55×55×96 ReLpool1 3×3 2 - 27×27×96
conv2 5×5 1 - 27×27×96 ReL
pool2 3×3 2 - 13×13×256
conv3 3×3 1 - 13×13×384 ReL
conv4 3×3 1 - 13×13×384 ReL
conv5 3×3 1 - 13×13×256 ReL
pool5 3×3 2 - 6×6×256
fc6 - - - 1×1×4096 ReL
fc7 - - - 1×1×4096 ReLfc8 - - - 1×1×1000 softmax
def inference(self, images_placeholder, keep_prob): # 第 1畳み込みレイヤー with tf.name_scope('conv1') as scope: W_conv1 = self.weight_variable([11, 11, 3, 96]) b_conv1 = self.bias_variable([96]) h_conv1 = tf.nn.relu(self.conv2d(images_placeholder, W_conv1, stride=4, padding='VALID') + b_conv1) # 第 1プーリング層 with tf.name_scope('pool1') as scope: h_pool1 = self.max_pool_2x2(h_conv1, ksize=3, stride=2, padding='VALID')
# 第 2畳み込みレイヤー with tf.name_scope('conv2') as scope: W_conv2 = self.weight_variable([5, 5, 96, 96]) b_conv2 = self.bias_variable([96]) h_conv2 = tf.nn.relu(self.conv2d(h_pool1, W_conv2, stride=1, padding='VALID') + b_conv2) # 第 2プーリング層 with tf.name_scope('pool2') as scope: h_pool2 = self.max_pool_2x2(h_conv2, ksize=3, stride=2, padding='VALID')
省略・・・ # 第 8全結合レイヤー with tf.name_scope('fc8') as scope: W_fc8 = self.weight_variable([1000, self.NUMBER_OF_CLASSES]) b_fc8 = self.bias_variable([self.NUMBER_OF_CLASSES]) y_conv = tf.matmul(h_fc7, W_fc8) + b_fc8 return y_conv
Karabiner.inc
Chainer実装class CNN(Chain): def __init__(self): self._train = True super(CNN,self).__init__( conv1=L.Convolution2D(3, 96, 11, stride=4), conv2=L.Convolution2D(96, 256, 5, stride=1), conv3=L.Convolution2D(256, 384, 3, stride=1), conv4=L.Convolution2D(384, 384, 3, stride=1), conv5=L.Convolution2D(384, 256, 3, stride=1), fc6=L.Linear(9216, 4096), fc7=L.Linear(4096, 4096), fc8=L.Linear(4096, 1000), )
def forward(self, x, train=True): conv1 = F.relu(self.conv1(x)) pool1 = F.max_pooling_2d(conv1, 3, stride=2) conv2 = F.relu(self.conv2(pool1)) pool2 = F.max_pooling_2d(conv2, 3, stride=2) conv3 = F.relu(self.conv3(pool2)) conv4 = F.relu(self.conv4(conv3)) conv5 = F.relu(self.conv5(conv4)) pool5 = F.max_pooling_2d(conv5, 3, stride=2) fc6 = F.relu(self.fc6(pool5)) fc7 = F.relu(self.fc7(fc6)) y = self.fc8(fc7) return y
Python
name filter stride paddingoutput
map size function
data - - - 227×227×3 -conv1 11×11 4 - 55×55×96 ReLpool1 3×3 2 - 27×27×96
conv2 5×5 1 - 27×27×96 ReL
pool2 3×3 2 - 13×13×256
conv3 3×3 1 - 13×13×384 ReL
conv4 3×3 1 - 13×13×384 ReL
conv5 3×3 1 - 13×13×256 ReL
pool5 3×3 2 - 6×6×256
fc6 - - - 1×1×4096 ReL
fc7 - - - 1×1×4096 ReLfc8 - - - 1×1×1000 softmax
Karabiner.inc
まとめ
• Kerasは直感的にかつシンプルにモデルの構築ができるため、プロトタイプの作成には便利!
• 学習済みのモデルを使用して、特徴抽出や Fine-tuningも楽々!