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

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

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

Jupyter (旧IPython notebook)は、Notebook形式でドキュメント作成し、プログラムの記述・実行、その実行結果を記録するツールです。メモの作成や保存、共有、確認などもブラウザ上で行うことができます。

Keras

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

Python

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

Q&A

解決済

1回答

5856閲覧

kerasでVGG16のfine-tuningを行った際のエラー

kusaaaaaaaaa

総合スコア15

Jupyter

Jupyter (旧IPython notebook)は、Notebook形式でドキュメント作成し、プログラムの記述・実行、その実行結果を記録するツールです。メモの作成や保存、共有、確認などもブラウザ上で行うことができます。

Keras

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

Python

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

0グッド

0クリップ

投稿2018/10/25 02:25

前提・実現したいこと

プログラミング、機械学習初心者です。知識不足ですがよろしくお願いします。
初心者がてら、qitta上の興味のあるページで行っている実装を、そのままコピペして自分の環境でも実装してみたいと思い、
以下のサイトを参考にし、同じ事を実装しようとしました。
https://qiita.com/taku-buntu/items/305d8eb16e9502b09ed1
使用したのはここで紹介している以下のgithubのコードで、同じjupyterで実装しました。
https://github.com/taku-buntu/killme_adversarial_example_with_TensorFlow-Keras

in[5]まではエラーが出なかったのですが、
in[6]のfinetuningを行う所で以下のようなエラーが出てしまいました。
どの様に対処すればエラーが出ないのか教えて頂きたいです。

エラーメッセージ

ValueError Traceback (most recent call last)
<ipython-input-6-ce0f8b31cc97> in <module>
1 batch_size = 32
2
----> 3 vgg16 = tf.keras.applications.VGG16(include_top=False, weights='imagenet', classes=7, input_shape=(128, 128, 3))
4 vgg16.trainable = False
5

~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\keras\applications\vgg16.py in VGG16(include_top, weights, input_tensor, input_shape, pooling, classes)
125 data_format=K.image_data_format(),
126 require_flatten=include_top,
--> 127 weights=weights)
128
129 if input_tensor is None:

~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\keras\applications\imagenet_utils.py in _obtain_input_shape(input_shape, default_size, min_size, data_format, require_flatten, weights)
306 if input_shape[0] != 3 and weights == 'imagenet':
307 raise ValueError('The input must have 3 channels; got '
--> 308 'input_shape=' + str(input_shape) + '')
309 if ((input_shape[1] is not None and input_shape[1] < min_size) or
310 (input_shape[2] is not None and input_shape[2] < min_size)):

ValueError: The input must have 3 channels; got input_shape=(128, 128, 3)

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

win10
python3.6.6
jupyter

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

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

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

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

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

kusaaaaaaaaa

2018/10/25 02:53

全く変えず、コピペで実装しましたが、エラーが出てしまいました。
guest

回答1

0

ベストアンサー

top_model = tf.keras.Model(inputs=inputs, outputs=out) model = tf.keras.Model(inputs=vgg16.input, outputs=top_model(vgg16.output))

top_model = tf.keras.models.Model(inputs=inputs, outputs=out) model = tf.keras.models.Model(inputs=vgg16.input, outputs=top_model(vgg16.output))

にした以外はそのままのコードで動きましたよ。

TensorFlow のバージョンは 1.4.1 です。
いくつのバージョンのをお使いなのでしょうか?

追記

元の Notebook は不完全な点が見受けられたので、書き直しました。

キルミーの学習済みモデルで行うAdvarsal Example

キルミーの方は各クラスのデータ数が以下のようになっており、汎化性能のある分類器をつくるという点では完全にデータ不足です。

class name: agiri class id: 0 number of images: 44 class name: botsu class id: 1 number of images: 10 class name: others class id: 2 number of images: 64 class name: sonya class id: 3 number of images: 175 class name: yasuna class id: 4 number of images: 341 class name: yasuna&agiri class id: 5 number of images: 4 class name: yasuna&sonya class id: 6 number of images: 47

そのため、ImageNet の VGG16 学習済みモデルで Advarsal Example を作成する例も記載しました。
猫をくじゃくと誤認させる Adversal Example を生成させています。
実行には imagenet_class_index.json を ipynb と同じディレクトリにダウンロードして、置いてください。

ImageNet の学習済みモデルで行うAdvarsal Example

追記

キルミーのほうは学習データが少なすぎて、仮に100%近い精度が出たとしてもそれはあくまで学習したデータに対してなので、汎化性能はないでしょうし、意味がないと考えています。
もしやるなら、キルミーではなく、最初から「26クラス約3000枚の画像」のほうでやってみたらどうでしょうか。
収束しないときは以下をいろいろ変えてみるとよいと思います。

x = Dense(100, activation='relu')(x) # 識別層の次元数 x = Dropout(0.5)(x) # ドロップアウトの脱落率 model.compile(loss='categorical_crossentropy', # 学習方法 optimizer='adam', metrics=['accuracy'])

エラーですが、sample.jpg は適当に用意して ipynb と同じディレクトリに配置してください。猫を使いましたが、犬とか鳥とか ImageNet の 1000 カテゴリならなんでもいいです。

投稿2018/10/25 03:09

編集2018/11/06 05:36
tiitoi

総合スコア21956

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

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

kusaaaaaaaaa

2018/10/25 03:36 編集

1.9.0を使っています。 上記の箇所を変えたり、1.4.1にダウングレードして試してみましたが、同じエラーが出てしまいました。 もし他に原因があるとしたら、何があるでしょうか?
tiitoi

2018/10/25 03:51

ダウングレードは pip install tensorflow-gpu==1.4.1 でしましたか?またダウングレードした際に一旦、「Kernel」→「Shutdown」より Notebook をシャットダウンして、再度開く必要があります。開いたままですと、import tensorflow をすでに実行済みであれば、もう一度やってもキャッシュが使われてしまうので。
kusaaaaaaaaa

2018/10/25 04:11 編集

すみません、うまくダウングレード出来ていなかったかもしれません。再度上記の通りに実行したのですが、 1.4.1は無いとエラーが出てしまいました。 Could not find a version that satisfies the requirement tensorflow-gpu==1.4.1 (from versions: 1.2.0rc2, 1.2.0, 1.2.1, 1.3.0rc0, 1.3.0rc1, 1.3.0rc2, 1.3.0, 1.4.0rc0, 1.4.0rc1, 1.4.0, 1.5.0rc0, 1.5.0rc1, 1.5.0, 1.5.1, 1.6.0rc0, 1.6.0rc1, 1.6.0, 1.7.0rc0, 1.7.0rc1, 1.7.0, 1.7.1, 1.8.0rc0, 1.8.0rc1, 1.8.0, 1.9.0rc0, 1.9.0rc1, 1.9.0rc2, 1.9.0, 1.10.0rc0, 1.10.0rc1, 1.10.0, 1.11.0rc0, 1.11.0rc1, 1.11.0rc2, 1.11.0, 1.12.0rc0, 1.12.0rc1) No matching distribution found for tensorflow-gpu==1.4.1 また、1.9.0では出来ない事が、1.4.1では出来る様な事があるのでしょうか?
kusaaaaaaaaa

2018/10/25 04:15

すみません、一つ違いを見つけたのですが、 in[1]を実行した際に、 出力?としてピンク色の背景で何かしら出力されていると思うのですが、(下記 ) /home/takusub/.pyenv/versions/anaconda3-5.1.0/envs/TensorFlow/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters 自分の場合何も出てこず、反応がありませんでしたが、エラーが出ていた訳では無かったので、スルーしていました。
tiitoi

2018/10/25 04:16

1.4.0 はあるみたいですね。1.4.0 で試しても動きました。 ちなみに CPU 版は tensorflow==1.4.0 GPU版は tensorflow-gpu==1.4.0 と名前が違うので注意してください。
kusaaaaaaaaa

2018/10/25 04:37

tf-gpu1.4.0に変更したところ in[1]で下記のようなエラーが出ました。 OSError Traceback (most recent call last) ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\platform\self_check.py in preload_check() 61 try: ---> 62 ctypes.WinDLL(build_info.nvcuda_dll_name) 63 except OSError: ~\Miniconda3\envs\mykeras\lib\ctypes\__init__.py in __init__(self, name, mode, handle, use_errno, use_last_error) 347 if handle is None: --> 348 self._handle = _dlopen(self._name, mode) 349 else: OSError: [WinError 126] 指定されたモジュールが見つかりません。 During handling of the above exception, another exception occurred: ImportError Traceback (most recent call last) <ipython-input-1-c6fcd5814e27> in <module> ----> 1 import tensorflow as tf 2 import numpy as np 3 import matplotlib 4 import matplotlib.pyplot as plt 5 get_ipython().run_line_magic('matplotlib', 'inline') ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\__init__.py in <module> 22 23 # pylint: disable=wildcard-import ---> 24 from tensorflow.python import * 25 # pylint: enable=wildcard-import 26 ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\__init__.py in <module> 47 import numpy as np 48 ---> 49 from tensorflow.python import pywrap_tensorflow 50 51 # Protocol buffers ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\pywrap_tensorflow.py in <module> 28 # Perform pre-load sanity checks in order to produce a more actionable error 29 # than we get from an error during SWIG import. ---> 30 self_check.preload_check() 31 32 # pylint: disable=wildcard-import,g-import-not-at-top,unused-import,line-too-long ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\platform\self_check.py in preload_check() 68 "'C:\Windows\System32'. If it is not present, ensure that you " 69 "have a CUDA-capable GPU with the correct driver installed." ---> 70 % build_info.nvcuda_dll_name) 71 72 if hasattr(build_info, "cudart_dll_name") and hasattr( ImportError: Could not find 'nvcuda.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Typically it is installed in 'C:\Windows\System32'. If it is not present, ensure that you have a CUDA-capable GPU with the correct driver installed. また、先ほどまで使っていた1.9.0の時にin[1]を入力した際、ピンク色の背景の出力?が出ていなかった事にも気づきました。 過去にgpuを使用してdeepを行っていなかった事も原因なのかもしれません。
tiitoi

2018/10/25 04:40

FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. これは h5py というモジュールが numpy の deprecated な API を使っていることに起因する warning なので、今回の件には関係ありません。
tiitoi

2018/10/25 04:42 編集

いままで、GPU または CPU のどちらの tensorflow を使っていたのですか?CPU 版使ってたのにGPUを使ったのでしたら、上記のエラーになります。
kusaaaaaaaaa

2018/10/25 04:43

今までCPUを使っていました。初歩的なミスでしたら申し訳ないです。 どの様に対処すれば良いでしょうか?
tiitoi

2018/10/25 04:46

間違ってGPU版を入れてしまったのだと思いますので、まず pip uninstall tensorflow-gpu でアンイストール pip install tensorflow=1.4.0 で tensorflow 1.4.0 をインストール Notebook は 「Kernel」→「Shutdown」より Notebook をシャットダウンして、再度開く そして実行してみてください。
kusaaaaaaaaa

2018/10/25 05:01

インストール等は完了したのですが、やはり同じエラーが出てしまいました。 このソースコードが元々GPUとして作られているのかもしれないのですが、cpu用に変更する処理が必要だったりするのでしょうか? in[1]にgpuに関するコードがあったので気になりました。 下記in[1]です。 import tensorflow as tf import numpy as np import matplotlib import matplotlib.pyplot as plt %matplotlib inline import os import cv2 from PIL import Image config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True)) sess = tf.Session(config=config) tf.keras.backend.set_session(sess)
tiitoi

2018/10/25 05:13

以下のように変更して CPU 版 1.4.0 でも動きました。 ``` config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True)) sess = tf.Session(config=config) tf.keras.backend.set_session(sess) ``` ↓ ``` sess = tf.Session() tf.keras.backend.set_session(sess) ```
tiitoi

2018/10/25 05:15

ちなみに kill_me_images 以下に kill_me_baby_datasets.zip という zip ファイルがありますが、それはちゃんと解凍されてますよね?
kusaaaaaaaaa

2018/10/25 05:59

はい、kill_me_images\kill_me_baby_datasetsは解凍されているのでin[5]でラベルの認識はされています。 上記の様にCPU用に変更しましたが、またも同じエラーが出てしまいました。
tiitoi

2018/10/25 07:14

取りあえず最新版でも動いたので pip install --upgrade tensorflow で 1.11.0 にしてください。 インストール後に以下のようにバージョンが表示されることを確認してみてください。 import tensorflow as tf print(tf.__version__) # 1.11.0 となることを確認してください。 エラーが出ているのは、 ``` vgg16 = tf.keras.applications.VGG16(include_top=False, weights='imagenet', classes=7, input_shape=(128, 128, 3)) ``` でしょうか?上記バージョンでエラーなくその部分は通りました。
kusaaaaaaaaa

2018/10/29 03:47

最新版でインストールしましたが上記の vgg16 = tf.keras.applications.VGG16(include_top=False, weights='imagenet', classes=7, input_shape=(128, 128, 3)) でエラーが出てしまいました。 多分データセットは関係なくVGGモデルのファインチューニングがうまく出来ていないのだと思い、 ファインチューニングせずVGG16の元のモデルを動かしてみたところ、以下のように動きました。 import tensorflow as tf import numpy as np import matplotlib import matplotlib.pyplot as plt %matplotlib inline import os import cv2 from PIL import Image sess = tf.Session() tf.keras.backend.set_session(sess) from keras.applications.vgg16 import VGG16 model = VGG16(include_top=True, weights='imagenet', input_tensor=None, input_shape=None) Using TensorFlow backend. Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels.h5 553467904/553467096 [==============================] - 666s 1us/step しかし、 vgg16 = tf.keras.applications.VGG16(include_top=False, weights='imagenet', classes=7, input_shape=(128, 128, 3)) にしたところ、やはり同様のエラーが起こってしまいました。
kusaaaaaaaaa

2018/10/29 04:10

すみません、少し進展がありました。 以前(128,128,3)の様に(a,b,c)のようなところを(c,a,b)のような順番に直したところ、エラーが治った前例があり、それを試してみたところ先程の箇所でのエラーは出なくなりました。しかし、また違うところでよくわからないエラー(下記)が出てしまいました。 Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5 58892288/58889256 [==============================] - 35s 1us/step Found 685 images belonging to 7 classes. Epoch 1/100 --------------------------------------------------------------------------- InvalidArgumentError Traceback (most recent call last) <ipython-input-8-9a5440c10be4> in <module> 33 34 # 学習開始! ---> 35 model.fit_generator(train_generator, steps_per_epoch=train_generator.samples//batch_size, epochs=100, callbacks=ckps) 36 model.save("models/killme_vgg16.h5") 37 ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\keras\engine\training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch) 2063 use_multiprocessing=use_multiprocessing, 2064 shuffle=shuffle, -> 2065 initial_epoch=initial_epoch) 2066 2067 def evaluate_generator(self, ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\keras\engine\training_generator.py in fit_generator(model, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch) 169 170 outs = model.train_on_batch( --> 171 x, y, sample_weight=sample_weight, class_weight=class_weight) 172 173 if not isinstance(outs, list): ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\keras\engine\training.py in train_on_batch(self, x, y, sample_weight, class_weight) 1826 1827 self._make_train_function() -> 1828 outputs = self.train_function(ins) 1829 1830 if len(outputs) == 1: ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\keras\backend.py in __call__(self, inputs) 2973 feed_symbols != self._feed_symbols or self.fetches != self._fetches or 2974 session != self._session): -> 2975 self._make_callable(feed_arrays, feed_symbols, symbol_vals, session) 2976 2977 fetched = self._callable_fn(*array_vals, ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\keras\backend.py in _make_callable(self, feed_arrays, feed_symbols, symbol_vals, session) 2918 callable_opts.run_options.CopyFrom(self.run_options) 2919 # Create callable. -> 2920 callable_fn = session._make_callable_from_options(callable_opts) 2921 # Cache parameters corresponding to the generated callable, so that 2922 # we can detect future mismatches and refresh the callable. ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\client\session.py in _make_callable_from_options(self, callable_options) 1429 """ 1430 self._extend_graph() -> 1431 return BaseSession._Callable(self, callable_options) 1432 1433 ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\client\session.py in __init__(self, session, callable_options) 1383 with errors.raise_exception_on_not_ok_status() as status: 1384 self._handle = tf_session.TF_SessionMakeCallable( -> 1385 session._session, options_ptr, status) 1386 finally: 1387 tf_session.TF_DeleteBuffer(options_ptr) ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\framework\errors_impl.py in __exit__(self, type_arg, value_arg, traceback_arg) 524 None, None, 525 compat.as_text(c_api.TF_Message(self.status.status)), --> 526 c_api.TF_GetCode(self.status.status)) 527 # Delete the underlying status object from memory otherwise it stays alive 528 # as there is a reference to status from this from the traceback due to InvalidArgumentError: Default MaxPoolingOp only supports NHWC on device type CPU [[{{node block1_pool/MaxPool}} = MaxPool[T=DT_FLOAT, data_format="NCHW", ksize=[1, 1, 2, 2], padding="VALID", strides=[1, 1, 2, 2], _device="/job:localhost/replica:0/task:0/device:CPU:0"](block1_conv2/Relu)]] 解決方法がありましたら、よろしくお願いします。
tiitoi

2018/10/29 04:28 編集

vgg16 = tf.keras.applications.VGG16(include_top=False, weights='imagenet', classes=7, input_shape=(128, 128, 3)) はファインチューニングしているわけではなく、学習済みのVGGモデルを構築しているだけです。 from keras.applications.vgg16 import VGG16 model = VGG16(include_top=True, weights='imagenet', input_tensor=None, input_shape=None) とやっていることは同じなはずです。 (a,b,c)のようなところを(c,a,b)にしたら、そこは通ったということは、VGG16 モデルのクラス作成がなぜか (H, W, C) ではなく、(C, H, W) になっているということでしょうか? Tensorflow では (H, W, C) の channel_last がデフォルトなはずです。 ドキュメントと見たところ、 > Note that when using TensorFlow, for best performance you should set image_data_format='channels_last' in your Keras config at ~/.keras/keras.json. と書いてあったので、~/.keras/keras.json を開いて `"image_data_format": "channels_last"` となっていることを確認してみてください。
kusaaaaaaaaa

2018/10/29 09:44

長々と質問に対して親切に回答してくださって、ありがとうございます。 以前もfirstをlastに直していたのですが、アップデート等でlastになっていたようです。 該当箇所を直したところ、無事にepoch100/100まで学習に成功したのですが、その次のモデルの保存の所で以下のエラーが出てしまいました。 Epoch 98/100 21/21 [==============================] - 96s 5s/step - loss: 0.0572 - acc: 0.9940 Epoch 99/100 21/21 [==============================] - 90s 4s/step - loss: 0.0271 - acc: 0.9955 Epoch 100/100 21/21 [==============================] - 87s 4s/step - loss: 0.0876 - acc: 0.9866 --------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-6-48cc34acea7b> in <module> 32 # 学習開始! 33 model.fit_generator(train_generator, steps_per_epoch=train_generator.samples//batch_size, epochs=100, callbacks=ckps) ---> 34 model.save("models/killme_vgg16.h5") 35 36 sess = tf.keras.backend.get_session() ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\keras\engine\network.py in save(self, filepath, overwrite, include_optimizer) 1359 1360 from tensorflow.python.keras.models import save_model # pylint: disable=g-import-not-at-top -> 1361 save_model(self, filepath, overwrite, include_optimizer) 1362 1363 def save_weights(self, filepath, overwrite=True, save_format=None): ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\keras\engine\saving.py in save_model(model, filepath, overwrite, include_optimizer) 87 return 88 ---> 89 f = h5py.File(filepath, mode='w') 90 opened_new_file = True 91 else: ~\Miniconda3\envs\mykeras\lib\site-packages\h5py\_hl\files.py in __init__(self, name, mode, driver, libver, userblock_size, swmr, **kwds) 310 with phil: 311 fapl = make_fapl(driver, libver, **kwds) --> 312 fid = make_fid(name, mode, userblock_size, fapl, swmr=swmr) 313 314 if swmr_support: ~\Miniconda3\envs\mykeras\lib\site-packages\h5py\_hl\files.py in make_fid(name, mode, userblock_size, fapl, fcpl, swmr) 146 fid = h5f.create(name, h5f.ACC_EXCL, fapl=fapl, fcpl=fcpl) 147 elif mode == 'w': --> 148 fid = h5f.create(name, h5f.ACC_TRUNC, fapl=fapl, fcpl=fcpl) 149 elif mode == 'a': 150 # Open in append mode (read/write). h5py\_objects.pyx in h5py._objects.with_phil.wrapper() h5py\_objects.pyx in h5py._objects.with_phil.wrapper() h5py\h5f.pyx in h5py.h5f.create() OSError: Unable to create file (unable to open file: name = 'models/killme_vgg16.h5', errno = 2, error message = 'No such file or directory', flags = 13, o_flags = 302) ファイルが作れない、存在しないことは理解できるのですが、修正方法が分からずまた躓いてしまいました。 もし対処法があるようでしたら、教えて頂きたいです。よろしくお願いします。
tiitoi

2018/10/29 09:54

出力先の models フォルダがなにのが原因なので、予め手動で models を .ipynb と同じディレクトリに作っておけばいいかと思います。
kusaaaaaaaaa

2018/10/30 07:09 編集

modelsフォルダが多く複雑になっていたため、フォルダを指定せず直接作成し、無事に保存することに成功しました。ありがとうございます。 続きでまたエラーが発生したため質問させていただきたいのですが、 https://qiita.com/taku-buntu/items/305d8eb16e9502b09ed1 上記のサイトの本命のadversarialexamplesという所までこれまで実装に成功したのですが 次のFine-tuningモデルをAdversarial Examples作成用に再編集という所のコード(modify_fine.py) でエラーが発生してしまいました。 githubでコードをまとめている方(https://github.com/taku-buntu/killme_adversarial_example_with_TensorFlow-Keras/blob/master/Kill_me_adversarial_example_with_TF.ipynb) ではIn[9]以降の所です。 in[9]in[10]は入力せずスルーしています。(していいのかわからないが) そして、in[12] y_pred = model.graph.get_tensor_by_name('model_1/activation_1/Softmax:0') y_logits = model.graph.get_tensor_by_name('model_1/logits/BiasAdd:0') input_img = model.graph.get_tensor_by_name('input_1:0') を走らせたところ、 AttributeError Traceback (most recent call last) <ipython-input-12-7e3d760932ff> in <module> ----> 1 y_pred = model.graph.get_tensor_by_name('model_1/activation_1/Softmax:0') 2 y_logits = model.graph.get_tensor_by_name('model_1/logits/BiasAdd:0') 3 input_img = model.graph.get_tensor_by_name('input_1:0') AttributeError: 'Model' object has no attribute 'graph' とエラーが出てしまいました。 [12]ではテンソルを指定しており、そこがコピペのせいで間違っていると思っていたのですが、 それ以前のコードのmodel.graphのところでエラーが出ているようです。(多分) tf.summary.FileWriter('bb', model.graph) というコードを走らせても同様のエラーが発生しました。bbはtensorboard用に出力したディレクトリです。このことからmodel.graphが怪しいと考えました。 モジュールが入っていないのか、パスが違うのか検討しましたが分からず躓いてしまったため、対処法を教えて頂きたいです。よろしくお願いします。
tiitoi

2018/10/30 11:13

エラー通りモデルオブジェクトは graph という attribute を持っていないというエラーです。 tf.Session() クラスが graph という Attribute を持っています。 現在実行している計算グラフは graph = tf.get_default_graph() と取得できます。
kusaaaaaaaaa

2018/10/31 04:47 編集

ありがとうございます。 tf.Session()クラスはin[1]で定義していると思うのですが、また別の処理が必要なのでしょうか? また、この質問の最初の回答で、Modelをmodels.Modelに変更とありましたが、そこが影響しているのでしょうか? もしよろしければ、どの様な処理をすれば良いのか、コードを入力すればよいのか教えて頂きたいです。
kusaaaaaaaaa

2018/11/05 03:07 編集

何度も申し訳ございません。 非常に長い日数と時間をかけてしまっている事は十分承知なのですが、このエラーが解決できれば無事に成功しそうなので、どうかよろしくおねがいします。
tiitoi

2018/11/05 03:15

Jupyter Notebook はセルを消しても変数の状態が残るので、実行したセルが今公開されてる ipynb 上に残っていないのではないでしょうか。セルの右側に実行番号があるのですが、それが連番になっていないことからも順番に実行されていないことがわかります。 これまでのやり取りからもわかるように、元の Notebook がそのまま実行しても動かない、不完全な状態であると考えているので、時間があるときに試してみようと思っていたのですが、ちょっとまだ試せていません。
kusaaaaaaaaa

2018/11/05 03:49

回答ありがとうございます。 model.graph = tf.Graph()  と入力してみたところ、in[12]で先程のエラーは出なくなり、無事に実行できました。 しかし、同じin[12]のところで以下のようなエラーが出てしまいました。 入力 y_pred = model.graph.get_tensor_by_name('model/activation/Softmax:0') y_logits = model.graph.get_tensor_by_name('model/logits/BiasAdd:0') input_img = model.graph.get_tensor_by_name('input_1:0') 出力 KeyError Traceback (most recent call last) <ipython-input-53-53a9969c1e65> in <module> ----> 1 y_pred = model.graph.get_tensor_by_name('model/activation/Softmax:0') 2 y_logits = model.graph.get_tensor_by_name('model/logits/BiasAdd:0') 3 input_img = model.graph.get_tensor_by_name('input_1:0') ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\framework\ops.py in get_tensor_by_name(self, name) 3662 raise TypeError("Tensor names are strings (or similar), not %s." % 3663 type(name).__name__) -> 3664 return self.as_graph_element(name, allow_tensor=True, allow_operation=False) 3665 3666 def _get_tensor_by_tf_output(self, tf_output): ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\framework\ops.py in as_graph_element(self, obj, allow_tensor, allow_operation) 3486 3487 with self._lock: -> 3488 return self._as_graph_element_locked(obj, allow_tensor, allow_operation) 3489 3490 def _as_graph_element_locked(self, obj, allow_tensor, allow_operation): ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\framework\ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation) 3528 raise KeyError("The name %s refers to a Tensor which does not " 3529 "exist. The operation, %s, does not exist in the " -> 3530 "graph." % (repr(name), repr(op_name))) 3531 try: 3532 return op.outputs[out_n] KeyError: "The name 'model/activation/Softmax:0' refers to a Tensor which does not exist. The operation, 'model/activation/Softmax', does not exist in the graph." こちらの入力はmodel/activation/softmaxというテンソルにアクセスするコードだと思うのですが、 エラーが出てしまいました。 参考にしている(お手本の環境) https://qiita.com/taku-buntu/items/305d8eb16e9502b09ed1 では'model_1/activation_1/Softmax:0'としていますが、これはこの人の環境下においてactibvation_1のような表示がtensorboadに書いてあったため、その様に入力しているのだと思いますが(サイト上のコードとgithub上のコードはなぜか違っており見本の環境下もいまいち参考にならないが^^;)、 私の環境下においてtensorboadでグラフを表示してみたところ、 model/activation/Softmaxだったためこの様に入力したのですがその様なテンソルは無いという様なエラーが出てしまいました。 実際の自分の環境下のテンソルボードのキャプチャです。↓ http://firestorage.jp/download/9605a35e76d688e921da7ee22b4be11298e627c2 正確にアクセスしたと思ったのですがエラーが出てしまいましたので、何か対処法がございましたら教えて頂きたいです。
tiitoi

2018/11/05 03:57

コード見てみるので、なにかわかったら追記しますね。
kusaaaaaaaaa

2018/11/05 04:05 編集

ありがとうございます。追記ですいません。 そもそも[12]を入力する必要はあるのでしょうか? [17]の様な入力をすればy=pred y=logits input_imgを定義できてると思います。 [12]をすっ飛ばし、[17]の定義を入力し、[13]を試したところ 入力 with model.graph.as_default(): pl_cls_target = tf.placeholder(dtype=tf.int32, name='pl_cls_target') loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y_logits, labels=[pl_cls_target], name='sparse_loss') gradient = tf.gradients(loss, input_img, name='adv_gradient') sess = tf.keras.backend.get_session() saver = tf.train.Saver() saver.save(sess, "killme_vgg16/killme_vgg16.ckpt") 出力 ValueError Traceback (most recent call last) <ipython-input-58-49de312b5b39> in <module> 2 pl_cls_target = tf.placeholder(dtype=tf.int32, name='pl_cls_target') 3 ----> 4 loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y_logits, labels=[pl_cls_target], name='sparse_loss') 5 gradient = tf.gradients(loss, input_img, name='adv_gradient') 6 ~\Miniconda3\envs\mykeras\lib\site-packages\tensorflow\python\ops\nn_ops.py in sparse_softmax_cross_entropy_with_logits(_sentinel, labels, logits, name) 2055 if logits.get_shape().ndims is not None and logits.get_shape().ndims == 0: 2056 raise ValueError( -> 2057 "Logits cannot be scalars - received shape %s." % logits.get_shape()) 2058 if logits.get_shape().ndims is not None and ( 2059 labels_static_shape.ndims is not None and ValueError: Logits cannot be scalars - received shape (). 何かしら値を有していないように思えるのですが、こちらのエラーに関しても何かわかったら教えていただきたいです。よろしくおねがいします。
kusaaaaaaaaa

2018/11/06 02:37

連日お世話になってます。試行錯誤したところ、エラーを回避する事ができまして、in[26]の最終的な出力まで実行する事ができました。これで終わったと思ったのですが、2つ程問題が発生してしまいました。 1つ目がイテレーションを何度行っても目標とするスコアが出なかった事です。 どこか配列の入力が正確に行われていない事が原因なのでしょうか? 2つ目が日本語フォントが見つからないとの事です。 その結果が以下になります。 in[26] 入力 img_path = 'kill_me_images/kill_me_baby_datasets/yasuna/01_034.png' cls_tar = 3 print(class_list[cls_tar]) image_source, adv_img, noise = adversarial_example(img_path=img_path, cls_tar=cls_tar, noise_limit=1.2, required_score=0.99, iterations=1000) 出力(省略) sonya INFO:tensorflow:Restoring parameters from killme_vgg16/killme_vgg16.ckpt イテレーション: 0 Source score: 100.00%, class-number: 4, class-name: yasuna Target score: 0.00%, class-number: 3, class-name: sonya Gradient min: -2.448285, max: 3.612494, stepsize: 1.94 イテレーション: 1 Source score: 100.00%, class-number: 4, class-name: yasuna Target score: 0.00%, class-number: 3, class-name: sonya Gradient min: -1.806917, max: 3.266325, stepsize: 2.14 イテレーション: 2 Source score: 100.00%, class-number: 4, class-name: yasuna Target score: 0.00%, class-number: 3, class-name: sonya Gradient min: -1.793985, max: 3.043883, stepsize: 2.30 イテレーション: 3 Source score: 100.00%, class-number: 4, class-name: yasuna Target score: 0.00%, class-number: 3, class-name: sonya Gradient min: -1.505358, max: 2.908875, stepsize: 2.41 イテレーション: 4 Source score: 100.00%, class-number: 4, class-name: yasuna Target score: 0.00%, class-number: 3, class-name: sonya Gradient min: -1.666222, max: 2.806515, stepsize: 2.49 イテレーション: 5 Source score: 100.00%, class-number: 4, class-name: yasuna Target score: 0.00%, class-number: 3, class-name: sonya Gradient min: -1.375475, max: 2.768321, stepsize: 2.53 イテレーション: 6 Source score: 99.99%, class-number: 4, class-name: yasuna Target score: 0.00%, class-number: 3, class-name: sonya Gradient min: -1.652928, max: 2.812083, stepsize: 2.49 . . . イテレーション: 997 Source score: 99.97%, class-number: 4, class-name: yasuna Target score: 0.00%, class-number: 3, class-name: sonya Gradient min: -1.342439, max: 2.311816, stepsize: 3.03 イテレーション: 998 Source score: 99.98%, class-number: 4, class-name: yasuna Target score: 0.00%, class-number: 3, class-name: sonya Gradient min: -1.635821, max: 2.295986, stepsize: 3.05 イテレーション: 999 Source score: 99.97%, class-number: 4, class-name: yasuna Target score: 0.00%, class-number: 3, class-name: sonya Gradient min: -1.371922, max: 2.306402, stepsize: 3.04 --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-82-b182e7f4580f> in <module> 3 4 print(class_list[cls_tar]) ----> 5 image_source, adv_img, noise = adversarial_example(img_path=img_path, cls_tar=cls_tar, noise_limit=1.2, required_score=0.99, iterations=1000) <ipython-input-79-e7580ba1b697> in adversarial_example(img_path, cls_tar, noise_limit, required_score, iterations) 10 score_source_org=prob_source, 11 score_target=score_target, ---> 12 probs=probs) 13 14 # Print some statistics for the noise. <ipython-input-78-5d9122ccd779> in plot_images(image, noise, noisy_image, name_source, name_target, score_source, score_source_org, score_target, probs, top_k) 81 # in a single Notebook cell. 82 ---> 83 plt.savefig('kill_me_images/gen_adv/{}_to_{}.png'.format(name_source, name_target)) 84 85 plt.show() ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\pyplot.py in savefig(*args, **kwargs) 686 def savefig(*args, **kwargs): 687 fig = gcf() --> 688 res = fig.savefig(*args, **kwargs) 689 fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors 690 return res ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\figure.py in savefig(self, fname, frameon, transparent, **kwargs) 2095 self.set_frameon(frameon) 2096 -> 2097 self.canvas.print_figure(fname, **kwargs) 2098 2099 if frameon: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs) 2073 orientation=orientation, 2074 bbox_inches_restore=_bbox_inches_restore, -> 2075 **kwargs) 2076 finally: 2077 if bbox_inches and restore_bbox: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs) 508 509 """ --> 510 FigureCanvasAgg.draw(self) 511 renderer = self.get_renderer() 512 ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self) 400 toolbar = self.toolbar 401 try: --> 402 self.figure.draw(self.renderer) 403 # A GUI class may be need to update a window using this draw, so 404 # don't forget to call the superclass. ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\figure.py in draw(self, renderer) 1650 1651 mimage._draw_list_compositing_images( -> 1652 renderer, self, artists, self.suppressComposite) 1653 1654 renderer.close_group('figure') ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite) 136 if not_composite or not has_images: 137 for a in artists: --> 138 a.draw(renderer) 139 else: 140 # Composite any adjacent images together ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe) 2602 renderer.stop_rasterizing() 2603 -> 2604 mimage._draw_list_compositing_images(renderer, self, artists) 2605 2606 renderer.close_group('axes') ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite) 136 if not_composite or not has_images: 137 for a in artists: --> 138 a.draw(renderer) 139 else: 140 # Composite any adjacent images together
kusaaaaaaaaa

2018/11/06 02:38

~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\axis.py in draw(self, renderer, *args, **kwargs) 1197 self._update_label_position(renderer) 1198 -> 1199 self.label.draw(renderer) 1200 1201 self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2) ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\text.py in draw(self, renderer) 707 708 with _wrap_text(self) as textobj: --> 709 bbox, info, descent = textobj._get_layout(renderer) 710 trans = textobj.get_transform() 711 ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\text.py in _get_layout(self, renderer) 302 tmp, lp_h, lp_bl = renderer.get_text_width_height_descent('lp', 303 self._fontproperties, --> 304 ismath=False) 305 offsety = (lp_h - lp_bl) * self._linespacing 306 ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in get_text_width_height_descent(self, s, prop, ismath) 216 217 flags = get_hinting_flag() --> 218 font = self._get_agg_font(prop) 219 font.set_text(s, 0.0, flags=flags) 220 w, h = font.get_width_height() # width and height of unrotated string ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in _get_agg_font(self, prop) 251 """ 252 fname = findfont(prop) --> 253 font = get_font(fname) 254 255 font.clear() ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\font_manager.py in get_font(filename, hinting_factor) 1286 if hinting_factor is None: 1287 hinting_factor = rcParams['text.hinting_factor'] -> 1288 return _get_font(filename, hinting_factor) 1289 1290 FileNotFoundError: [Errno 2] No such file or directory: '/usr/share/fonts/truetype/fonts-japanese-gothic.ttf' Error in callback <function install_repl_displayhook.<locals>.post_execute at 0x00000274B1222598> (for post_execute): --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\pyplot.py in post_execute() 107 def post_execute(): 108 if matplotlib.is_interactive(): --> 109 draw_all() 110 111 # IPython >= 2 ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\_pylab_helpers.py in draw_all(cls, force) 130 for f_mgr in cls.get_all_fig_managers(): 131 if force or f_mgr.canvas.figure.stale: --> 132 f_mgr.canvas.draw_idle() 133 134 atexit.register(Gcf.destroy_all) ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backend_bases.py in draw_idle(self, *args, **kwargs) 1897 if not self._is_idle_drawing: 1898 with self._idle_draw_cntx(): -> 1899 self.draw(*args, **kwargs) 1900 1901 def draw_cursor(self, event): ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self) 400 toolbar = self.toolbar 401 try: --> 402 self.figure.draw(self.renderer) 403 # A GUI class may be need to update a window using this draw, so 404 # don't forget to call the superclass. ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\figure.py in draw(self, renderer) 1650 1651 mimage._draw_list_compositing_images( -> 1652 renderer, self, artists, self.suppressComposite) 1653 1654 renderer.close_group('figure') ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite) 136 if not_composite or not has_images: 137 for a in artists: --> 138 a.draw(renderer) 139 else: 140 # Composite any adjacent images together ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe) 2602 renderer.stop_rasterizing() 2603 -> 2604 mimage._draw_list_compositing_images(renderer, self, artists) 2605 2606 renderer.close_group('axes') ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite) 136 if not_composite or not has_images: 137 for a in artists: --> 138 a.draw(renderer) 139 else: 140 # Composite any adjacent images together ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\axis.py in draw(self, renderer, *args, **kwargs) 1197 self._update_label_position(renderer) 1198 -> 1199 self.label.draw(renderer) 1200 1201 self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2) ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None:
kusaaaaaaaaa

2018/11/06 02:38

~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\text.py in draw(self, renderer) 707 708 with _wrap_text(self) as textobj: --> 709 bbox, info, descent = textobj._get_layout(renderer) 710 trans = textobj.get_transform() 711 ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\text.py in _get_layout(self, renderer) 302 tmp, lp_h, lp_bl = renderer.get_text_width_height_descent('lp', 303 self._fontproperties, --> 304 ismath=False) 305 offsety = (lp_h - lp_bl) * self._linespacing 306 ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in get_text_width_height_descent(self, s, prop, ismath) 216 217 flags = get_hinting_flag() --> 218 font = self._get_agg_font(prop) 219 font.set_text(s, 0.0, flags=flags) 220 w, h = font.get_width_height() # width and height of unrotated string ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in _get_agg_font(self, prop) 251 """ 252 fname = findfont(prop) --> 253 font = get_font(fname) 254 255 font.clear() ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\font_manager.py in get_font(filename, hinting_factor) 1286 if hinting_factor is None: 1287 hinting_factor = rcParams['text.hinting_factor'] -> 1288 return _get_font(filename, hinting_factor) 1289 1290 FileNotFoundError: [Errno 2] No such file or directory: '/usr/share/fonts/truetype/fonts-japanese-gothic.ttf' --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) ~\Miniconda3\envs\mykeras\lib\site-packages\IPython\core\formatters.py in __call__(self, obj) 339 pass 340 else: --> 341 return printer(obj) 342 # Finally look for special method names 343 method = get_real_method(obj, self.print_method) ~\Miniconda3\envs\mykeras\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig) 242 243 if 'png' in formats: --> 244 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs)) 245 if 'retina' in formats or 'png2x' in formats: 246 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs)) ~\Miniconda3\envs\mykeras\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs) 126 127 bytes_io = BytesIO() --> 128 fig.canvas.print_figure(bytes_io, **kw) 129 data = bytes_io.getvalue() 130 if fmt == 'svg': ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs) 2047 orientation=orientation, 2048 dryrun=True, -> 2049 **kwargs) 2050 renderer = self.figure._cachedRenderer 2051 bbox_artists = kwargs.pop("bbox_extra_artists", None) ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs) 508 509 """ --> 510 FigureCanvasAgg.draw(self) 511 renderer = self.get_renderer() 512 ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self) 400 toolbar = self.toolbar 401 try: --> 402 self.figure.draw(self.renderer) 403 # A GUI class may be need to update a window using this draw, so 404 # don't forget to call the superclass. ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\figure.py in draw(self, renderer) 1650 1651 mimage._draw_list_compositing_images( -> 1652 renderer, self, artists, self.suppressComposite) 1653 1654 renderer.close_group('figure') ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite) 136 if not_composite or not has_images: 137 for a in artists: --> 138 a.draw(renderer) 139 else: 140 # Composite any adjacent images together ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe) 2602 renderer.stop_rasterizing() 2603 -> 2604 mimage._draw_list_compositing_images(renderer, self, artists) 2605 2606 renderer.close_group('axes') ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite) 136 if not_composite or not has_images: 137 for a in artists: --> 138 a.draw(renderer) 139 else: 140 # Composite any adjacent images together ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\axis.py in draw(self, renderer, *args, **kwargs) 1197 self._update_label_position(renderer) 1198 -> 1199 self.label.draw(renderer) 1200 1201 self._update_offset_text_position(ticklabelBoxes, ticklabelBoxes2) ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs) 48 renderer.start_filter() 49 ---> 50 return draw(artist, renderer, *args, **kwargs) 51 finally: 52 if artist.get_agg_filter() is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\text.py in draw(self, renderer) 707 708 with _wrap_text(self) as textobj: --> 709 bbox, info, descent = textobj._get_layout(renderer) 710 trans = textobj.get_transform() 711 ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\text.py in _get_layout(self, renderer) 302 tmp, lp_h, lp_bl = renderer.get_text_width_height_descent('lp', 303 self._fontproperties, --> 304 ismath=False) 305 offsety = (lp_h - lp_bl) * self._linespacing 306 ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in get_text_width_height_descent(self, s, prop, ismath) 216 217 flags = get_hinting_flag() --> 218 font = self._get_agg_font(prop) 219 font.set_text(s, 0.0, flags=flags) 220 w, h = font.get_width_height() # width and height of unrotated string ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\backends\backend_agg.py in _get_agg_font(self, prop) 251 """ 252 fname = findfont(prop) --> 253 font = get_font(fname) 254 255 font.clear() ~\Miniconda3\envs\mykeras\lib\site-packages\matplotlib\font_manager.py in get_font(filename, hinting_factor) 1286 if hinting_factor is None: 1287 hinting_factor = rcParams['text.hinting_factor'] -> 1288 return _get_font(filename, hinting_factor) 1289 1290 FileNotFoundError: [Errno 2] No such file or directory: '/usr/share/fonts/truetype/fonts-japanese-gothic.ttf' <Figure size 1440x720 with 4 Axes> 何か解決方法がありましたら教えて頂きたいです。
kusaaaaaaaaa

2018/11/06 02:57

これまでのgithubとのソースコードとの変更点、エラーの対処等をまとめておきます。 変更点1 in[1] config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True)) sess = tf.Session(config=config) tf.keras.backend.set_session(sess) ``` ↓ ``` sess = tf.Session() tf.keras.backend.set_session(sess) 変更点2 in[6] top_model = tf.keras.Model(inputs=inputs, outputs=out) model = tf.keras.Model(inputs=vgg16.input, outputs=top_model(vgg16.output)) を top_model = tf.keras.models.Model(inputs=inputs, outputs=out) model = tf.keras.models.Model(inputs=vgg16.input, outputs=top_model(vgg16.output)) 変更点3 モデルの使用方法の変更 現在は学習させたものをそのまま使っておらず、一度保存したものを使用しており、以下のように出力して再現しています。 from keras.models import load_model model = load_model('killme_vgg16.h5') model.load_weights('killme_vgg16_weights.h5') 変更点4 in[12]において以下の様なエラーの発生 AttributeError: 'Model' object has no attribute 'graph ↓ model.graph = tf.Graph() の入力によって解決。 変更点5 in[12]周辺 使用するテンソル名の変更 これは自分の環境下でそのような名前だったためそうしただけ。 model/activation_1/Softmax:0 ↓ model/activation/Softmax:0 変更点6 in[12]において、変更点5の用にテンソル名を自分の環境下に合わせたのにもかかわらずエラーが出たが、下記のように変更した結果エラーを回避した。 y_pred = model.graph.get_tensor_by_name('model/activation/Softmax:0') y_logits = model.graph.get_tensor_by_name('model/logits/BiasAdd:0') input_img = model.graph.get_tensor_by_name('input_1:0') ↓ y_pred = graph.get_tensor_by_name('model/activation/Softmax:0') y_logits = graph.get_tensor_by_name('model/logits/BiasAdd:0') input_img = graph.get_tensor_by_name('input_1:0')
tiitoi

2018/11/06 03:59

元のコードは不完全な点が見受けられたので、書き直した Notebook を追記しました。 キルミー以外に ImageNet の学習済みモデルでも試してみました。
tiitoi

2018/11/06 04:00 編集

--- 二重投稿になってしまったのでこちらを削除 ---
kusaaaaaaaaa

2018/11/06 05:23 編集

回答ありがとうございます。 キルミーの方では最後の出力までエラーなく出力する事ができました。 しかし、出力結果の様にイテレーションを何度行っても目標となるスコアが出ませんでした。 ↓ http://xfs.jp/f6dX7q これはtiitoiさんの言うデータセット不足からくる不完全な点が影響しているのでしょうか? それともまた別の原因なのでしょうか? ここまで動かすことが出来て非常に嬉しいので、こちらのキルミーの方でも成功させたいと考えています。個人的には自前のデータセット(26クラス約3000枚の画像)を用いてAdversarialExamplesを作る事が目標なので、キルミーの画像を自前のデータにすり変えて実行出来たら良いなと考えていました。 また、tiitiさんが追記して頂いた方に関してですが、こちらも学習済みVGG16に自前のデータセットでファインチューニングを行い、自前のデータセットの画像のAdversarialExamplesを作りたいと考えております。 もし、その様な変更に対応できるようでしたらコードを教えていただきたいです。よろしくおねがいします。 追記して頂いたnotebookを実行してみたところ、 in[4]のところで以下の様なエラーが出てしまいました。 error Traceback (most recent call last) <ipython-input-4-19161f026c80> in <module> 13 14 img = cv2.imread('sample.jpg') # 画像を読み込む。 ---> 15 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # BGR -> RGB 16 img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC) # リサイズする。 17 error: OpenCV(3.4.3) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' 調べたのですがいまいち対処法がわからないので、どうすれば良いか教えていただきたいです。よろしくおねがいします。
tiitoi

2018/11/06 05:37

追記しました。 エラーのほうは適当に画像を持ってきて、cv2.imread() にそのパスを指定してください。画像は ImageNet のカテゴリに含まれるものです。動物とかがいいでしょう。
tiitoi

2018/11/06 05:41 編集

> キルミーの方では最後の出力までエラーなく出力する事ができました。 > しかし、出力結果の様にイテレーションを何度行っても目標となるスコアが出ませんでした。 これは回答に追記したNotebook の話か、Qiita の記事の人が作った Notebook の話かどちらですか?
kusaaaaaaaaa

2018/11/06 06:05

回答ありがとうございます。 tiitoiさんの追記して頂いた方で無事に実装に成功する事が出来ました。 本当にありがとうございます。 > キルミーの方では最後の出力までエラーなく出力する事ができました。 > しかし、出力結果の様にイテレーションを何度行っても目標となるスコアが出ませんでした。 こちらに関しては記事の人が作ったnotebookの方になります。
tiitoi

2018/11/06 06:15 編集

自分も記事の書いた人のパラメータでは学習が収束しなかったので、追記に書いた Notebook のように修正して 98% になりました。 記事のほうの Notebook は VGG16 用の前処理が間違ってたり (255 で割るのは VGG ではない) したので、あまり信用しないほうがよいかと思います。
kusaaaaaaaaa

2018/11/12 07:53

連日お世話になっております。 今回、追記して頂いたVGG16でimagenetを学習したモデルを利用したAdversarialExamplesの生成では、別のCNNモデル(Lenet-5)で自前のデータセットを学習したものを利用しAdversarial Examplesを生成したいと考えています。 (最終的にアルファベットを違うアルファベットに誤認識させる様なものを作りたいです。) しかし、追記して頂いたコードではVGG用の処理を行ってリサイズを行っていたりと、別のモデルに変更した際の処理がいまいち分からなくて躓いてしまいました。 また、モデルの変更に伴いlogitsのパスの指定の変更等もあると思うのですが。。。。 コードが汚くて申し訳ないのですが、以下が自前のデータセットと学習させたCNNモデルのコードのgithubになります。 https://github.com/posimiya99/new こちらの質問で追記して頂いたコードをどの様に変更すれば自前のgithubのモデルでも実装できるのか教えていただきたいです。よろしくおねがいします。
tiitoi

2018/11/13 06:56

Adversal Example を生成するモデルの仕組みは理解されてますか?元の ipynb の具体的にどこが不明なのかわからないと、すみませんが、アドバイスは難しいです。
kusaaaaaaaaa

2018/11/14 02:53

すみません。質問したいことが多くなってしまい、具体的な質問になっていませんでした。 長くなってしまいますが、一つづつ質問させて頂きます。 まず追記して頂いたコードではVGGの学習済みモデルを使っており、既にある imagenet_class_index.jsonで(num,en,ja)の正解ラベルを読み込んでいると思います。 自前のgithubでは、正解画像を読み込ませ、フォルダごとにラベル付けをしてlabel_listにAからZまでの26のラベルに分けています。 ここで、自前のgithubの方で行ったラベル付けを、追記して頂いたコードで使用しているimagenet_class_index.jsonの様なjsonファイルにするにはどの様な処理を行えばよろしいのでしょうか?アドバイスよろしくおねがいします。
tiitoi

2018/11/14 04:37

わざわざファイルにしなくても labels = ['A', 'B', 'C', ..., 'Z'] という結果を表示する際に使用するラベル名のリストを1つ作っておけばよいのではないでしょうか。
kusaaaaaaaaa

2018/11/14 05:10

ありがとうございます。 class_names = np.array(["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",]) のようにして定義する事が出来たので、無事に解決しました。 引き続き質問させて頂きます。 追記して頂いたコードでin[3]では from tensorflow.keras.applications.vgg16 import VGG16, preprocess_inputとし、 in[4]にて、 x = preprocess_input(img) # VGG16 用の前処理を行う。 のようにpreprocess_imput使っているのですが、今回私はVGG16ではなく違うモデル(lenet-5)を使用しております。 この様にモデルが変わった時にどの様に対処すればよいのか教えていただきたいです。 よろしくおねがいします。
tiitoi

2018/11/14 05:28 編集

前処理というのは、例えば画像を [0, 1] に正規化する、平均画像を引く (VGG16 とか) などです。 自作のモデルは前処理を行うかどうかも含めて質問者さんが決めることなので、なにもしないで画像をそのままネットワークに流すのであれば、なにもしなくていいです。 なにかする場合は、ネットワークにデータを流す前にそれを行ってください。
kusaaaaaaaaa

2018/11/14 07:28

回答ありがとうございます。今回前処理等を行わないつもりなのでin[4]のもともとのコードから x = preprocess_input(img) # VGG16 用の前処理を行う。 の行を削除すればよろしいのでしょうか?行ってみた結果、以下のようなエラーがでてしまいました。 UnboundLocalError Traceback (most recent call last) <ipython-input-6-490bffa50088> in <module> 16 17 # 推論する。 ---> 18 predict_single_img(img) 19 20 # 画像を描画する。 <ipython-input-6-490bffa50088> in predict_single_img(img) 1 def predict_single_img(img): ----> 2 x = np.expand_dims(x, axis=0) # バッチの次元を追加する。 3 4 # 推論する。 5 scores = model.predict(x)[0] UnboundLocalError: local variable 'x' referenced before assignment 1行消えたことでxが定義されなくなった事は分かるのですが、また新しくxを宣言しなければならないのでしょうか?予測をする際にxは必要となってくると思います。 もしくは、前処理をする際はこの1行を消す事自体あっている処理なのでしょうか? 前処理を行わない際の変更点を教えていただきたいです。
tiitoi

2018/11/14 09:10

変数名は適当に好きなものを使っていただければいいです。 np.expand_dims(img, axis=0) とすればよいのではないですか。
kusaaaaaaaaa

2018/11/16 03:30

np.expand_dims(img, axis=0) とすればよいとの事ですが 前処理の1行を削除しても 次の行に既に x = np.expand_dims(img, axis=0) があるので、何か新しく記述する必要は無いのではないでしょうか? なので、特に変更はせず前処理の1行を削除して実行してみたのですが 実行 def predict_single_img(img): x = np.expand_dims(x, axis=0) # バッチの次元を追加する。 # 推論する。 scores = model.predict(x)[0] top3_classes = scores.argsort()[-3:][::-1] # 推論結果を表示する。 for name, score in zip(class_names[top3_classes], scores[top3_classes]): print('{}: {:.2%}'.format(name, score)) print() img = cv2.imread('data/test/A/A0.png') # 画像を読み込む。 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # BGR -> RGB img = cv2.resize(img, (28, 28), interpolation=cv2.INTER_CUBIC) # リサイズする。 # 推論する。 predict_single_img(img) # 画像を描画する。 plt.axis('off') plt.imshow(img) plt.show() エラー --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-6-729b3de2a59e> in <module> 16 17 # 推論する。 ---> 18 predict_single_img(img) 19 20 # 画像を描画する。 <ipython-input-6-729b3de2a59e> in predict_single_img(img) 1 def predict_single_img(img): ----> 2 x = np.expand_dims(x, axis=0) # バッチの次元を追加する。 3 4 # 推論する。 5 scores = model.predict(x)[0] UnboundLocalError: local variable 'x' referenced before assignment 上記のエラーが試行錯誤しているコードです。↓ https://github.com/posimiya99/new/blob/master/tst.ipynb in[3]までが自前の学習モデルの構築 in[5]以降が追記していただいたコードを参考にしています。 in[6]では前処理を削除し、次の行で元から存在していた x = np.expand_dims(img, axis=0) のように宣言が行われているのですがエラーが出てしまいました。 アドバイスよろしくお願いします。
tiitoi

2018/11/16 03:50 編集

x = np.expand_dims(x, axis=0) を x = np.expand_dims(img, axis=0) と変えればよいのではということだったのですが。 まず一行一行なにをやっているのか理解してから、新しいことに取り組んでください。 意味を理解せずにコピペするからわからなくなります。 例えば、上記の例でいうと、img の形状はなにで、np.expand_dims() はなにをしていて、その返り値 x はどうなっているか理解されていますか?
kusaaaaaaaaa

2018/11/16 04:34

すみません、しっかり確認をしていませんでした。 np.expand_dimsで次元を増やし、返り値はxはnumpy配列で合っていますでしょうか? imgの形状はいまいち理解していませんでした。 この箇所に関するエラーは解決したと思うのですが、 実行してみると、以下のようなエラーが出てしまいました。 ValueError Traceback (most recent call last) <ipython-input-14-11eb48ed7ee1> in <module> 15 img = cv2.resize(img, (28, 28), interpolation=cv2.INTER_CUBIC) # リサイズする。 16 # 推論する。 ---> 17 predict_single_img(img) 18 19 # 画像を描画する。 <ipython-input-14-11eb48ed7ee1> in predict_single_img(img) 3 4 # 推論する。 ----> 5 scores = model.predict(x)[0] 6 top3_classes = scores.argsort()[-3:][::-1] 7 ~\Miniconda3\envs\mykeras\lib\site-packages\keras\engine\training.py in predict(self, x, batch_size, verbose, steps) 1147 'argument.') 1148 # Validate user data. -> 1149 x, _, _ = self._standardize_user_data(x) 1150 if self.stateful: 1151 if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0: ~\Miniconda3\envs\mykeras\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size) 749 feed_input_shapes, 750 check_batch_axis=False, # Don't enforce the batch size. --> 751 exception_prefix='input') 752 753 if y is not None: ~\Miniconda3\envs\mykeras\lib\site-packages\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix) 136 ': expected ' + names[i] + ' to have shape ' + 137 str(shape) + ' but got array with shape ' + --> 138 str(data_shape)) 139 return data 140 ValueError: Error when checking input: expected conv2d_1_input to have shape (3, 28, 28) but got array with shape (28, 28, 3) とエラーが出ました。 このエラーに関しては以前も経験しており、keras.jsonのdatafomatのfirst、lastを変更すれば解決したのですが、今回は少し問題があり、追記していただいたコードでは通るのにも関わらず、自分が書いたコードでは通らないということです。 実は少し前から疑問があり、追記して頂いたコードで期待されているVGG16の形は(3,224,224)だったと思います。 しかし、実際に中身を確認してみると(224,224,3)と出力されており、この形でコードが通っていました。 入力 def predict_single_img(img): x = preprocess_input(img) # VGG16 用の前処理を行う。 x = np.expand_dims(x, axis=0) # バッチの次元を追加する。 # 推論する。 scores = model.predict(x)[0] top3_classes = scores.argsort()[-3:][::-1] # 推論結果を表示する。 for name, score in zip(class_names[top3_classes], scores[top3_classes]): print('{}: {:.2%}'.format(name, score)) print() img = cv2.imread('orig/doraemon.jpg') # 画像を読み込む。 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # BGR -> RGB img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC) # リサイズする。 print(img.shape) 出力 (224, 224, 3) なので今回も大丈夫だろうと試したのですが、今回の様なエラーが出てしまいました。 追記して頂いたコードでは、lastでは通り、firstでは通りません。出力された形はどちらも(228,228,3)だったのですが、lastでは通りました。 自分のコードではlastでもfirstでも通りませんでした。 datafomatの所は関係ないという事でしょうか。 原因は何が考えられるでしょうか?アドバイスお願いします。
tiitoi

2018/11/16 05:18

predict() の直前で print(x.shape) として、(1, 28,28, 3) となっていることは確認していますか? 上のほうの image = image.transpose(2, 0, 1) はどのような意図で入れたのでしょうか?
kusaaaaaaaaa

2018/11/16 06:24

回答ありがとうございます。 imagetransposeを消し、predict() の直前で print(x.shape) とした所、(1, 28,28, 3) となっていました。以下のコードのin[10]になります。 https://github.com/posimiya99/new/blob/master/tstst2.ipynb 初めのほうのコードはあくまで学習済みのモデルの読み込みの為のコードであったため、特に意識せずimagetransposeを入れてしまいました。 アドバイスお願いします。
tiitoi

2018/11/16 06:37

> 特に意識せずimagetransposeを入れてしまいました。 image = image.transpose(2, 0, 1) は axis の入れ替えなので、元が (H, W, C) と並んでいたら、(C, H, W) にしていることを意味しています。 また model.summary() を見ると、最初の Conv2D 層は (None, 20, 28, 28) と (C, H, W) になっていますね。それに (H, W, C) オーダーのデータを入れようとしてエラーになっています。 'captcha_lenet.json' がモデル定義ファイルだと思うのですが、これはご自身で作られたものですか? モデルの定義が (C, H, W) オーダーになっています。
kusaaaaaaaaa

2018/11/22 03:50

ありがとうございます。もともとのモデルを(H,W,C)に直したところ、無事にエラーを回避し、画像の読み込みとラベルの予測の出力に成功しました。 次に、追記して頂いたコードのin[5]を実行するために、自分で構築したモデルのsoftmaxの直前のテンソル名を調べようとしたのですが、定義等がいまいちわからず次のコードの様に実行してtensorboardで表示してみたところ、 graph visualization failed: The graph is empty. Make sure that the graph is passed to the tf.summary.FileWritter after the graph is defined. 実行したコードは以下になります。 https://github.com/posimiya99/new/blob/master/tst4.ipynb テンソルボードでしっかい表示させるために、コードの定義等で追記するべき点があったら教えて頂きたいです。また、簡単に調べれる様でしたらテンソル名も教えて頂きたいです。よろしくお願いいたします。 ちなみに、モデルの構築は以下の様になります。 model = Sequential() model.add(Conv2D(20, kernel_size=5, padding="same", input_shape=(28,28,3))) model.add(Activation("relu")) model.add(MaxPooling2D()) model.add(Conv2D(50, kernel_size=5, border_mode="same")) model.add(Activation("relu")) model.add(MaxPooling2D()) model.add(Flatten()) model.add(Dense(500)) model.add(Activation("relu")) model.add(Dense(26)) model.add(Activation("softmax"))
kusaaaaaaaaa

2018/11/25 02:24

すみません、質問を変えさせてもよろしいでしょうか? 追記して頂いたgithub(https://github.com/nobetan/dl_examples/blob/master/adversal_example/adversal_example_imagenet.ipynb) ではin[5]において'predictions/BiasAdd:0'というテンソル名を取得していると思いますが、どのように取得しましたか? tf.Graph.get_tensor_by_name()のような関数で取得したのでしょうか?それともテンソルボードに表示したのでしょうか? どの様に取得したのかを教えて頂きたいです。よろしくお願いします。
tiitoi

2018/11/26 06:46

[print(n.name) for n in tf.get_default_graph().as_graph_def().node] で今のセッションにあるグラフの名前が表示されるので、model.summary() の結果を参考にすれば、該当のテンソルの名前が見つかると思います。
tiitoi

2018/11/26 06:48 編集

あと、コメント欄でやり取りしていると長くなって読みづらくなってしまうので、お手数ですが、この質問はクローズして、もし今後別の質問があれば、新規の質問として立てていただけないでしょうか?
kusaaaaaaaaa

2018/11/28 02:33

ありがとうございます。上記の様にグラフ名の一覧を取得して必要としていたテンソル名を把握し、エラーを回避することが出来ました。本当にありがとうございます。 引き続き実装を試みていたのですがまたエラーで躓いてしまったので、新しく質問させていただきました。 そちらのほうを見て頂けると幸いです、よろしくお願いします。 その質問が以下になります。 https://teratail.com/questions/160764
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問