質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

深層学習

深層学習は、多数のレイヤのニューラルネットワークによる機械学習手法。人工知能研究の一つでディープラーニングとも呼ばれています。コンピューター自体がデータの潜在的な特徴を汲み取り、効率的で的確な判断を実現することができます。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

1回答

1172閲覧

【Keras】自作モデルを使ったGrad-camを実装したいがエラーが出ます

JiN_grom

総合スコア4

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

深層学習

深層学習は、多数のレイヤのニューラルネットワークによる機械学習手法。人工知能研究の一つでディープラーニングとも呼ばれています。コンピューター自体がデータの潜在的な特徴を汲み取り、効率的で的確な判断を実現することができます。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2019/10/04 02:46

前提・実現したいこと

https://teratail.com/questions/102908の質問内容とほぼ被ってますが質問させていただきます。
2種類の画像分類を行うようなモデルを作成しました。その際、Resnet-50を使った転移学習によってモデルを構築しました。このモデルの中間層で行われている特徴量計算を可視化したいと考え、Grad-camを実装することとしました。

発生している問題・エラーメッセージ

Traceback (most recent call last): File "mygrad_cam.py", line 131, in <module> cam, heatmap = grad_cam(model, preprocessed_input, predicted_class, "activation_48") File "mygrad_cam.py", line 92, in grad_cam output_shape = target_category_loss_output_shape)) File "C:\Users\Public.MYCOMPUTER\Anaconda3\envs\tensor_copy\lib\site-packages\tensorflow\python\training\checkpointable\base.py", line 474, in _method_wrapper method(self, *args, **kwargs) File "C:\Users\Public.MYCOMPUTER\Anaconda3\envs\tensor_copy\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 140, in add 'Found: ' + str(layer)) TypeError: The added layer must be an instance of class Layer. Found: <keras.layers.core.Lambda object at 0x000002445C0646A0>

該当のソースコード

Python

1from keras.preprocessing import image 2from keras.layers.core import Lambda 3from tensorflow.python.keras.models import Sequential ,load_model 4from tensorflow.python.framework import ops 5import keras.backend as K 6import tensorflow as tf 7import numpy as np 8import keras 9import sys 10import cv2 11 12def target_category_loss(x, category_index, nb_classes): 13 return tf.multiply(x, K.one_hot([category_index], nb_classes)) 14 15def target_category_loss_output_shape(input_shape): 16 return input_shape 17 18def normalize(x): 19 # utility function to normalize a tensor by its L2 norm 20 return x / (K.sqrt(K.mean(K.square(x))) + 1e-5) 21 22def load_image(path): 23 img_path = path 24 img = image.load_img(img_path, target_size=(224,224)) 25 x = image.img_to_array(img) 26 x = np.expand_dims(x, axis=0) 27 return x 28 29def register_gradient(): 30 if "GuidedBackProp" not in ops._gradient_registry._registry: 31 @ops.RegisterGradient("GuidedBackProp") 32 def _GuidedBackProp(op, grad): 33 dtype = op.inputs[0].dtype 34 return grad * tf.cast(grad > 0., dtype) * \ 35 tf.cast(op.inputs[0] > 0., dtype) 36 37def compile_saliency_function(model, activation_layer='conv2d_3'): 38 input_img = model.input 39 layer_dict = dict([(layer.name, layer) for layer in model.layers[1:]]) 40 layer_output = layer_dict[activation_layer].output 41 max_output = K.max(layer_output, axis=3) 42 saliency = K.gradients(K.sum(max_output), input_img)[0] 43 return K.function([input_img, K.learning_phase()], [saliency]) 44 45def modify_backprop(model, name): 46 g = tf.get_default_graph() 47 with g.gradient_override_map({'Relu': name}): 48 49 # get layers that have an activation 50 layer_dict = [layer for layer in model.layers[1:] 51 if hasattr(layer, 'activation')] 52 53 # replace relu activation 54 for layer in layer_dict: 55 if layer.activation == keras.activations.relu: 56 layer.activation = tf.nn.relu 57 58 # re-instanciate a new model 59 new_model = model 60 return new_model 61 62def deprocess_image(x): 63 ''' 64 Same normalization as in: 65 https://github.com/fchollet/keras/blob/master/examples/conv_filter_visualization.py 66 ''' 67 if np.ndim(x) > 3: 68 x = np.squeeze(x) 69 # normalize tensor: center on 0., ensure std is 0.1 70 x -= x.mean() 71 x /= (x.std() + 1e-5) 72 x *= 0.1 73 74 # clip to [0, 1] 75 x += 0.5 76 x = np.clip(x, 0, 1) 77 78 # convert to RGB array 79 x *= 255 80 if K.image_dim_ordering() == 'th': 81 x = x.transpose((1, 2, 0)) 82 x = np.clip(x, 0, 255).astype('uint8') 83 return x 84 85def grad_cam(input_model, image, category_index, layer_name): 86 model = Sequential() 87 model.add(input_model) 88 89 nb_classes = 2 90 target_layer = lambda x: target_category_loss(x, category_index, nb_classes) 91 model.add(Lambda(target_layer, 92 output_shape = target_category_loss_output_shape)) 93 94 loss = K.sum(model.layers[-1].output) 95 conv_output = [l for l in model.layers[0].layers if l.name == layer_name][0].output 96 grads = normalize(K.gradients(loss, conv_output)[0]) 97 gradient_function = K.function([model.layers[0].input], [conv_output, grads]) 98 99 output, grads_val = gradient_function([image]) 100 output, grads_val = output[0, :], grads_val[0, :, :, :] 101 102 weights = np.mean(grads_val, axis = (0, 1)) 103 cam = np.ones(output.shape[0 : 2], dtype = np.float32) 104 105 for i, w in enumerate(weights): 106 cam += w * output[:, :, i] 107 108 cam = cv2.resize(cam, (64, 64)) 109 cam = np.maximum(cam, 0) 110 heatmap = cam / np.max(cam) 111 112 #Return to BGR [0..255] from the preprocessed image 113 image = image[0, :] 114 image -= np.min(image) 115 image = np.minimum(image, 255) 116 117 cam = cv2.applyColorMap(np.uint8(255*heatmap), cv2.COLORMAP_JET) 118 cam = np.float32(cam) + np.float32(image) 119 cam = 255 * cam / np.max(cam) 120 return np.uint8(cam), heatmap 121 122# 判定画像の読み込み 123preprocessed_input = load_image('F6.jpg') 124 125model = load_model('allnet.h5') 126model.summary() 127 128predictions = model.predict(preprocessed_input) 129 130predicted_class = np.argmax(predictions) 131cam, heatmap = grad_cam(model, preprocessed_input, predicted_class, "activation_48") 132cv2.imwrite("gradcam.jpg", cam) 133 134register_gradient() 135guided_model = modify_backprop(model, 'GuidedBackProp') 136saliency_fn = compile_saliency_function(guided_model) 137saliency = saliency_fn([preprocessed_input, 0]) 138gradcam = saliency[0] * heatmap[..., np.newaxis] 139cv2.imwrite("guided_gradcam.jpg", deprocess_image(gradcam))

試したこと

複数のサイトを参考にしながら色々と試してはみたのですが、どれを使ってもうまく実装することができませんでした。
ご教授のほどよろしくお願いいたします。

補足情報(FW/ツールのバージョンなど)

実行環境
Window10
AnacondaNavigator
Keras2.2.4
Tensorflow1.12.0

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

下記にモデル構造貼ってあります
※字数制限で途中略してあります


Layer (type) Output Shape Param # Connected to

input_1 (InputLayer) (None, 224, 224, 3) 0


conv1_pad (ZeroPadding2D) (None, 230, 230, 3) 0 input_1[0][0]


conv1 (Conv2D) (None, 112, 112, 64) 9472 conv1_pad[0][0]


bn_conv1 (BatchNormalization) (None, 112, 112, 64) 256 conv1[0][0]


activation (Activation) (None, 112, 112, 64) 0 bn_conv1[0][0]


pool1_pad (ZeroPadding2D) (None, 114, 114, 64) 0 activation[0][0]


max_pooling2d (MaxPooling2D) (None, 56, 56, 64) 0 pool1_pad[0][0]


res2a_branch2a (Conv2D) (None, 56, 56, 64) 4160 max_pooling2d[0][0]


bn2a_branch2a (BatchNormalizati (None, 56, 56, 64) 256 res2a_branch2a[0][0]


activation_1 (Activation) (None, 56, 56, 64) 0 bn2a_branch2a[0][0]


res2a_branch2b (Conv2D) (None, 56, 56, 64) 36928 activation_1[0][0]

activation_46 (Activation) (None, 7, 7, 512) 0 bn5c_branch2a[0][0] __________________________________________________________________________________________________ res5c_branch2b (Conv2D) (None, 7, 7, 512) 2359808 activation_46[0][0] __________________________________________________________________________________________________ bn5c_branch2b (BatchNormalizati (None, 7, 7, 512) 2048 res5c_branch2b[0][0] __________________________________________________________________________________________________ activation_47 (Activation) (None, 7, 7, 512) 0 bn5c_branch2b[0][0] __________________________________________________________________________________________________ res5c_branch2c (Conv2D) (None, 7, 7, 2048) 1050624 activation_47[0][0] __________________________________________________________________________________________________ bn5c_branch2c (BatchNormalizati (None, 7, 7, 2048) 8192 res5c_branch2c[0][0] __________________________________________________________________________________________________ add_15 (Add) (None, 7, 7, 2048) 0 bn5c_branch2c[0][0] activation_45[0][0] __________________________________________________________________________________________________ activation_48 (Activation) (None, 7, 7, 2048) 0 add_15[0][0] __________________________________________________________________________________________________ sequential (Sequential) (None, 1) 25690625 activation_48[0][0] ================================================================================================== Total params: 49,278,337 Trainable params: 49,225,217 Non-trainable params: 53,120 __________________________________________________________________________________________________

投稿2019/10/04 03:03

JiN_grom

総合スコア4

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問