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

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

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

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

Anaconda

Anacondaは、Python本体とPythonで利用されるライブラリを一括でインストールできるパッケージです。環境構築が容易になるため、Python開発者間ではよく利用されており、商用目的としても利用できます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

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

Q&A

0回答

1076閲覧

cleverhansを使用して敵対的サンプルを生成したい

mannmosu2011

総合スコア12

Keras

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

Anaconda

Anacondaは、Python本体とPythonで利用されるライブラリを一括でインストールできるパッケージです。環境構築が容易になるため、Python開発者間ではよく利用されており、商用目的としても利用できます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

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

0グッド

0クリップ

投稿2019/07/22 07:28

前提・実現したいこと

Anaconda3を使用し、Python3.7.3でkerasとtensorflowを用いてVGG16をファインチューニングして、作成したモデルに対して、cleverhansを使いAdversarial examplesの画像を作成したい

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

Exception Traceback (most recent call last) <ipython-input-15-279e7a133606> in <module> 7 fgsm_params = {'eps': 0.25, 'clip_min': 0.0, 'clip_max': 1.0} 8 # adversarial examples ----> 9 x_adv = fgsm.generate(x, **fgsm_params) C:\open\GitHub\cleverhans\cleverhans\attacks\fast_gradient_method.py in generate(self, x, **kwargs) 48 assert self.parse_params(**kwargs) 49 ---> 50 labels, _nb_classes = self.get_or_guess_labels(x, kwargs) 51 52 return fgm( C:\open\GitHub\cleverhans\cleverhans\attacks\attack.py in get_or_guess_labels(self, x, kwargs) 276 labels = kwargs['y_target'] 277 else: --> 278 preds = self.model.get_probs(x) 279 preds_max = reduce_max(preds, 1, keepdims=True) 280 original_predictions = tf.to_float(tf.equal(preds, preds_max)) C:\open\GitHub\cleverhans\cleverhans\utils_keras.py in get_probs(self, x) 183 :return: A symbolic representation of the probs 184 """ --> 185 name = self._get_softmax_name() 186 187 return self.get_layer(x, name) C:\open\GitHub\cleverhans\cleverhans\utils_keras.py in _get_softmax_name(self) 124 if 'activation' in cfg and cfg['activation'] == 'softmax': 125 return layer.name --> 126 raise Exception("No softmax layers found") 127 128 def _get_abstract_layer_name(self): Exception: No softmax layers found

該当のソースコード

Python

1import cv2 2import datetime 3 4fileName = r"C:\Users\imcla\Anaconda\open\src8\images\photo\image1.jpg" 5 6print(fileName) 7 8capture = cv2.VideoCapture(0) 9 10while(True): 11 ret, image = capture.read() 12 cv2.imshow(fileName,image) 13 if cv2.waitKey(1) & 0xFF == ord('p'): 14 cv2.imwrite(fileName, image) 15 break 16 17capture.release() 18cv2.destroyAllWindows() 19 20# -*- coding:utf-8 -*- 21 22from PIL import Image 23import os 24 25imgNames = os.listdir("images/photo/")#画像が保存されてるディレクトリへのpath 26 27def readImg(imgName): 28 try: #tryを使ってエラーでプログラムが止まっちゃうのを回避します。 29 img_src = Image.open("images/photo/"+ imgName)#pathは上で設定したのと同じ場所です。 30 print("read img!")#動いていることを確認するために書きましたがなくても全然OKです 31 except: #ゴミを読み込んだらこれちゃうで!って言います。 32 print("{} is not image file!".format(imgName)) 33 img_src = 1 34 return img_src 35 36for imgName in imgNames: 37 img_src = readImg(imgName) 38 if img_src == 1:continue 39 else: 40 resizedImg = img_src.resize((160,160)) # 41 resizedImg.save("images/photo/"+"160_160_"+imgName)#名前は長くなっちゃうけど仕方ない。 42 print(imgName+" is done!") 43 44#ライブラリの読み込み 45from keras.applications.vgg16 import VGG16 46from keras.preprocessing.image import ImageDataGenerator 47from keras.models import Sequential, Model 48from keras.layers import Input, Activation, Dropout, Flatten, Dense 49from keras.preprocessing.image import ImageDataGenerator 50from keras import optimizers 51 52# 分類するクラス 53root_dir = 'images/train/' 54 55classes = sorted(os.listdir(path=root_dir)) 56nb_classes = len(classes) 57print("クラスリスト", classes) 58img_width, img_height = 160, 160 59# VGG16のロード。FC層は不要なので include_top=False 60input_tensor = Input(shape=(img_width, img_height, 3)) 61vgg16 = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor) 62 63# FC層の作成 64top_model = Sequential() 65top_model.add(Flatten(input_shape=vgg16.output_shape[1:])) 66top_model.add(Dense(256, activation='relu')) 67top_model.add(Dropout(0.5)) 68top_model.add(Dense(nb_classes, activation='softmax')) 69 70# VGG16とFC層を結合してモデルを作成 71vgg_model = Model(input=vgg16.input, output=top_model(vgg16.output)) 72from keras.models import load_model 73vgg_model.load_weights('./results/Final.h5') 74# テスト用のコード 75from keras.preprocessing import image 76import numpy as np 77import matplotlib.pyplot as plt 78 79# 画像を読み込んで予測する 80def img_predict(filename): 81 # 画像を読み込んで4次元テンソルへ変換 82 img = image.load_img(filename, target_size=(img_height, img_width)) 83 x = image.img_to_array(img) 84 x = np.expand_dims(x, axis=0) 85 # 学習時にImageDataGeneratorのrescaleで正規化したので同じ処理が必要 86 # これを忘れると結果がおかしくなるので注意 87 x = x / 255.0 88 #表示 89 plt.imshow(img) 90 plt.show() 91 # 指数表記を禁止にする 92 np.set_printoptions(suppress=True) 93 94 #画像の人物を予測 95 pred = vgg_model.predict(x)[0] 96 #結果を表示する 97 print(classes) 98 print(pred*100) 99 return pred 100 101import glob 102#テスト用の画像が入っているディレクトリのpathを()に入れてください 103test = glob.glob('images/photo/*') 104#数字は各自入力 105image_probs=img_predict(test[0]) 106 107from keras.backend import tensorflow_backend 108from cleverhans.utils_keras import KerasModelWrapper 109import tensorflow as tf 110model_cleverhans = KerasModelWrapper(vgg_model) 111 112# GPU configulations 113config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True)) 114session = tf.Session(config=config) 115tensorflow_backend.set_session(session) 116 117n_classes = 10 118n_channels = 3 119img_width = 160 120img_height = 160 121 122from cleverhans.attacks import FastGradientMethod 123# placeholders 124x = tf.placeholder(tf.float32, shape=(None, img_width, img_height, n_channels)) 125y = tf.placeholder(tf.float32, shape=(None, n_classes)) 126# method 127fgsm = FastGradientMethod(model_cleverhans, sess=session) 128fgsm_params = {'eps': 0.25, 'clip_min': 0.0, 'clip_max': 1.0} 129# adversarial examples 130x_adv = fgsm.generate(x, **fgsm_params)

試したこと

Exception: No softmax layers foundというエラーが出てるので、softmaxレイヤーをtensorboardで探してみました。
イメージ説明
これを見てみるとsoftmaxがあるのではと思ったのですが何度試してもダメでした。
ほかにもこちらのサイトを参考にcleverhansを使わないadversarial examplesも試してみたのですが、こちらでもできませんでした。

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

使用している環境は
winsows10 Home 1903
Anaconda Navvigator1.9.7
Keras 2.2.4
tensorflow-gpu 1.13.1
です。
どうしたらエラーが解決するのかもわからずここに質問させていただきました。
cleverhansの使い方があまりわかっていないです…
よろしければどうすればエラーが解消できそうか教えていただけないでしょうか。
雑な質問で申し訳ありませんがよろしくお願いします。

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

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

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

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

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

kane_study

2020/12/17 08:13

すみません。力にはなれませんが、私も似た様な事を目指してます。 何か分かれば書き込みます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

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

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

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

ただいまの回答率
85.49%

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

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

質問する

関連した質問