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

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

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

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

Python

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

Q&A

解決済

1回答

1692閲覧

モデルの読み込みがうまくいきません

pan_p

総合スコア3

Keras

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

Python

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

0グッド

0クリップ

投稿2021/12/03 10:31

前提・実現したいこと

Grad-CAM++を用いて特徴量を可視化したいと考えていますが、モデルを読み込んでそのエラーが理解できずにいます
colabを用いて動かしています

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

以下のエラーメッセージの意味が良く分かってないので、ご教示いただきたいです

AttributeError Traceback (most recent call last) <ipython-input-5-b82e58f706aa> 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-3-b1276e029972> in Grad_Cam_plus_plus(input_model, layer_name, x, row, col) 10 11 # 予測クラスの算出 ---> 12 predictions = model.predict(preprocessed_input) 13 class_idx = np.argmax(predictions[0]) 14 AttributeError: 'str' object has no attribute 'predict'

該当のソースコード

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 = "/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.")

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

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

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

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

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

guest

回答1

0

ベストアンサー

model = "/content/drive/MyDrive/ji/saved_model/my_model"

としておいて、

Grad_Cam_plus_plus(model, target_layer, img, row, col)

で呼び出し、

def Grad_Cam_plus_plus(input_model, layer_name, x, row, col):

で受け取って、

model = input_model

と代入し、

model.predict(preprocessed_input)

をするためには、

"/content/drive/MyDrive/ji/saved_model/my_model"がpredictというメソッドを持たなければなりませんが、それはないというエラーメッセージです。

.predictを使いたければ文字列ではなく学習済みモデルでなければなりません。

keras.models.load_modelを使いましょう。

投稿2021/12/03 10:56

編集2021/12/03 11:01
ppaul

総合スコア24666

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

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

pan_p

2021/12/06 04:33

無事解決しました ありがとうございます
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問