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

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

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

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

Google Colaboratory

Google Colaboratoryとは、無償のJupyterノートブック環境。教育や研究機関の機械学習の普及のためのGoogleの研究プロジェクトです。PythonやNumpyといった機械学習で要する大方の環境がすでに構築されており、コードの記述・実行、解析の保存・共有などが可能です。

機械学習

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

Python

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

Q&A

解決済

1回答

1568閲覧

レイヤーの読み込みで失敗してしまいます

pan_p

総合スコア3

Keras

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

Google Colaboratory

Google Colaboratoryとは、無償のJupyterノートブック環境。教育や研究機関の機械学習の普及のためのGoogleの研究プロジェクトです。PythonやNumpyといった機械学習で要する大方の環境がすでに構築されており、コードの記述・実行、解析の保存・共有などが可能です。

機械学習

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

Python

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

0グッド

0クリップ

投稿2021/12/06 05:45

編集2021/12/06 07:22

実現したいこと

Grad-CAM++を利用して注視領域を可視化したいです。
しかし、レイヤーの読み込みで、レイヤーが存在しないとなって失敗してしまいます。
レイヤー名はTensorBoardの出力をを参考にしてます

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

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-22-4e280938b6d4> in <module>() 7 8 img = img_to_array(load_img(image_path,target_size=(row,col,3))) ----> 9 img_GCAMplusplus = Grad_Cam_plus_plus(model, target_layer, img, row, col) 10 time = time.ctime() 11 img_Gplusplusname = image_path+time+"_GCAM++_%s.jpg" 1 frames /usr/local/lib/python3.7/dist-packages/keras/engine/training.py in get_layer(self, name, index) 2629 if layer.name == name: 2630 return layer -> 2631 raise ValueError(f'No such layer: {name}. Existing layers are ' 2632 f'{self.layers}.') 2633 raise ValueError('Provide either a layer name or layer index at ' ValueError: No such layer: batch_normalization. Existing layers are [<keras.engine.functional.Functional object at 0x7f34aca9a1d0>, <keras.layers.pooling.GlobalAveragePooling2D object at 0x7f34b967b090>, <keras.layers.core.dense.Dense object at 0x7f34b967ba90>, <keras.layers.core.dense.Dense object at 0x7f34b967aa10>].

該当のソースコード

python

1import pandas as pd 2import numpy as np 3import cv2 4import argparse 5import keras 6import time 7import sys 8from keras import backend as K 9from keras.preprocessing.image import array_to_img, img_to_array, load_img 10from keras.applications.resnet import ResNet50 11 12K.set_learning_phase(1) 13 14def Grad_Cam_plus_plus(input_model, layer_name, x, row, col): 15 16 model = input_model 17 18 # 前処理 19 X = np.expand_dims(x, axis=0) 20 X = X.astype('float32') 21 preprocessed_input = X / 255.0 22 23 24 # 予測クラスの算出 25 predictions = model.predict(preprocessed_input) 26 class_idx = np.argmax(predictions[0]) 27 28 # 使用する重みの抽出、高階微分の計算 29 class_output = model.layers[-1].output 30 conv_output = model.get_layer(layer_name).output 31 grads = K.gradients(class_output, conv_output)[0] 32 #first_derivative:1階微分 33 first_derivative = K.exp(class_output)[0][class_idx] * grads 34 #second_derivative:2階微分 35 second_derivative = K.exp(class_output)[0][class_idx] * grads * grads 36 #third_derivative:3階微分 37 third_derivative = K.exp(class_output)[0][class_idx] * grads * grads * grads 38 39 #関数の定義 40 gradient_function = K.function([model.input], [conv_output, first_derivative, second_derivative, third_derivative]) # model.inputを入力すると、conv_outputとgradsを出力する関数 41 42 43 conv_output, conv_first_grad, conv_second_grad, conv_third_grad = gradient_function([preprocessed_input]) 44 conv_output, conv_first_grad, conv_second_grad, conv_third_grad = conv_output[0], conv_first_grad[0], conv_second_grad[0], conv_third_grad[0] 45 46 #alphaを求める 47 global_sum = np.sum(conv_output.reshape((-1, conv_first_grad.shape[2])), axis=0) 48 alpha_num = conv_second_grad 49 alpha_denom = conv_second_grad*2.0 + conv_third_grad*global_sum.reshape((1,1,conv_first_grad.shape[2])) 50 alpha_denom = np.where(alpha_denom!=0.0, alpha_denom, np.ones(alpha_denom.shape)) 51 alphas = alpha_num / alpha_denom 52 53 #alphaの正規化 54 alpha_normalization_constant = np.sum(np.sum(alphas, axis = 0), axis = 0) 55 alpha_normalization_constant_processed = np.where(alpha_normalization_constant != 0.0, alpha_normalization_constant, np.ones(alpha_normalization_constant.shape)) 56 alphas /= alpha_normalization_constant_processed.reshape((1,1,conv_first_grad.shape[2])) 57 58 #wの計算 59 weights = np.maximum(conv_first_grad, 0.0) 60 deep_linearization_weights = np.sum((weights * alphas).reshape((-1, conv_first_grad.shape[2]))) 61 62 #Lの計算 63 grad_CAM_map = np.sum(deep_linearization_weights * conv_output, axis=2) 64 grad_CAM_map = np.maximum(grad_CAM_map, 0) 65 grad_CAM_map = grad_CAM_map / np.max(grad_CAM_map) 66 67 #ヒートマップを描く 68 grad_CAM_map = cv2.resize(grad_CAM_map, (row, col), cv2.INTER_LINEAR) 69 jetcam = cv2.applyColorMap(np.uint8(255 * grad_CAM_map), cv2.COLORMAP_JET) # モノクロ画像に疑似的に色をつける 70 jetcam = (np.float32(jetcam) + x / 2) # もとの画像に合成 71 72 return jetcam 73 74if __name__ == '__main__': 75 model = keras.models.load_model("/content/drive/MyDrive/ji/saved_model/my_model") 76 target_layer = 'batch_normalization' 77 image_path = '/content/drive/MyDrive/Cs-N013.jpg' 78 row = 224 79 col = 224 80 81 img = img_to_array(load_img(image_path,target_size=(row,col,3))) 82 img_GCAMplusplus = Grad_Cam_plus_plus(model, target_layer, img, row, col) 83 time = time.ctime() 84 img_Gplusplusname = image_path+time+"_GCAM++_%s.jpg" 85 cv2.imwrite(img_Gplusplusname, img_GCAMplusplus) 86 print("Completed.")

試したこと

いくつかレイヤー名を試してdenseの時のみエラーが下記のようになりました

--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-23-907724f744ec> in <module>() 7 8 img = img_to_array(load_img(image_path,target_size=(row,col,3))) ----> 9 img_GCAMplusplus = Grad_Cam_plus_plus(model, target_layer, img, row, col) 10 time = time.ctime() 11 img_Gplusplusname = image_path+time+"_GCAM++_%s.jpg" <ipython-input-18-02dcd9cea551> in Grad_Cam_plus_plus(input_model, layer_name, x, row, col) 16 class_output = model.layers[-1].output 17 conv_output = model.get_layer(layer_name).output ---> 18 grads = K.gradienttape(class_output, conv_output)[0] 19 #first_derivative:1階微分 20 first_derivative = K.exp(class_output)[0][class_idx] * grads AttributeError: module 'keras.backend' has no attribute 'gradienttape'

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

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

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

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

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

guest

回答1

0

自己解決

python

1tf.summary()

でレイヤー名を確認することでエラー回避

denseのエラー回避は以下のコードを冒頭に記述することで出来る

python

1import tensorflow as tf 2tf.compat.v1.disable_eager_execution()

投稿2021/12/08 02:22

pan_p

総合スコア3

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問