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

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

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

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

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

Python

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

Q&A

0回答

1417閲覧

Grad-CAMを自作モデルで使用したいが'int' object has no attribute 'dtype'が解決できません

koukimaru22

総合スコア6

Keras

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

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

Python

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

0グッド

0クリップ

投稿2019/10/19 07:25

前提・実現したいこと

前回の質問に引き続きエラー文で止まってしまいました。
エラー文で検索をかけても出てこなかったのでわかる方がいましたら教えてください。

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

AttributeError Traceback (most recent call last) <ipython-input-40-d05192aa47aa> in <module> 147 guided_model = modify_backprop(model, 'GuidedBackProp') 148 saliency_fn = compile_saliency_function(guided_model) --> 149 saliency = saliency_fn([preprocessed_input, 0]) 150 gradcam = saliency[0] * heatmap[..., np.newaxis] 151 cv2.imwrite("guided_gradcam01.jpg", deprocess_image(gradcam)) ~\Anaconda3\envs\tensorflow16\lib\site-packages\keras\backend\tensorflow_backend.py in __call__(self, inputs) 2713 return self._legacy_call(inputs) 2714 -> 2715 return self._call(inputs) 2716 else: 2717 if py_any(is_tensor(x) for x in inputs): ~\Anaconda3\envs\tensorflow16\lib\site-packages\keras\backend\tensorflow_backend.py in _call(self, inputs) 2653 array_vals.append( 2654 np.asarray(value, -> 2655 dtype=tf.as_dtype(tensor.dtype).as_numpy_dtype)) 2656 if self.feed_dict: 2657 for key in sorted(self.feed_dict.keys()): AttributeError: 'int' object has no attribute 'dtype'

該当のソースコード

python

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

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

_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 224, 224, 3) 0 _________________________________________________________________ block1_conv1 (Conv2D) (None, 224, 224, 64) 1792 _________________________________________________________________ block1_conv2 (Conv2D) (None, 224, 224, 64) 36928 _________________________________________________________________ block1_pool (MaxPooling2D) (None, 112, 112, 64) 0 _________________________________________________________________ block2_conv1 (Conv2D) (None, 112, 112, 128) 73856 _________________________________________________________________ block2_conv2 (Conv2D) (None, 112, 112, 128) 147584 _________________________________________________________________ block2_pool (MaxPooling2D) (None, 56, 56, 128) 0 _________________________________________________________________ block3_conv1 (Conv2D) (None, 56, 56, 256) 295168 _________________________________________________________________ block3_conv2 (Conv2D) (None, 56, 56, 256) 590080 _________________________________________________________________ block3_conv3 (Conv2D) (None, 56, 56, 256) 590080 _________________________________________________________________ block3_pool (MaxPooling2D) (None, 28, 28, 256) 0 _________________________________________________________________ block4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 _________________________________________________________________ block4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 _________________________________________________________________ block4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 _________________________________________________________________ block4_pool (MaxPooling2D) (None, 14, 14, 512) 0 _________________________________________________________________ block5_conv1 (Conv2D) (None, 14, 14, 512) 2359808 _________________________________________________________________ block5_conv2 (Conv2D) (None, 14, 14, 512) 2359808 _________________________________________________________________ block5_conv3 (Conv2D) (None, 14, 14, 512) 2359808 _________________________________________________________________ block5_pool (MaxPooling2D) (None, 7, 7, 512) 0 _________________________________________________________________ flatten (Flatten) (None, 25088) 0 _________________________________________________________________ fc1 (Dense) (None, 4096) 102764544 _________________________________________________________________ fc2 (Dense) (None, 4096) 16781312 _________________________________________________________________ predictions (Dense) (None, 1000) 4097000 ================================================================= Total params: 138,357,544 Trainable params: 138,357,544 Non-trainable params: 0 _________________________________________________________________

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

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

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

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

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

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

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

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

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問