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

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

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

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

Python 3.x

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

Q&A

解決済

1回答

2451閲覧

スタイル変換をしたいが、私だけ「Resource Exhausted Error」が発生します.

Mr.AK

総合スコア5

Keras

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

Python 3.x

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

0グッド

0クリップ

投稿2020/08/02 07:00

編集2020/08/02 17:53

前提・実現したいこと

参考書「PythonとKerasによるディープラーニング」でスタイル変換について勉強しています.

自分だけが以下のプログラムを実行すると「Resource Exhausted Error」が発生してしまいます.
※再起動等を繰り返してもエラーが出てしまいます.
※友達は、同じプログラムを実行してもエラーが発生せずに画像が生成されるそうです.

実行環境の問題だと思うのですが、なぜ自分だけこのようなエラーが出るのか、どうすれば解決できるのか教えて下さい!
お手数をおかけしますが、何卒お願いします。。。

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

ResourceExhaustedError: 2 root error(s) found. (0) Resource exhausted: OOM when allocating tensor with shape[3,200,200,128] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [[{{node gradients/strided_slice_6_grad/StridedSliceGrad}}]] Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. [[add_8/_197]] Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. (1) Resource exhausted: OOM when allocating tensor with shape[3,200,200,128] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [[{{node gradients/strided_slice_6_grad/StridedSliceGrad}}]] Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. 0 successful operations. 0 derived errors ignored.

該当のソースコード

参考書のプログラム ←このプログラムをもとに作成しました.
※変更点「imsaveモジュール」ではなく「imageioモジュール」にしました.
(使用しているバージョンで「imsaveモジュール」を使おうとするとエラーが発生してしまうため)

python

1# 変数の定義 2from keras.preprocessing.image import load_img, img_to_array 3 4target_image_path = './StyleTransfer/Elephant.jpg' 5style_reference_image_path = './StyleTransfer/transfer_style_reference.jpg' 6 7width, height = load_img(target_image_path).size 8img_height = 400 9img_width = int(width * img_height / height) 10 11# 画像処理を行う補助関数の定義 12import numpy as np 13from keras.applications import vgg19 14def preprocess_image(image_path): 15 img = load_img(image_path, target_size = (img_height, img_width)) 16 img = img_to_array(img) 17 img = np.expand_dims(img, axis = 0) 18 img = vgg19.preprocess_input(img) 19 return img 20def deprocess_image(x): 21 # ImageNetから平均ピクセルを取り除くことで、中心を0に設定する 22 # これによりvgg19.preprocess_inputによって実行された変換を逆にする 23 x[:, :, 0] += 103.939 24 x[:, :, 1] += 117.779 25 x[:, :, 2] += 123.68 26 # フォーマットをBGRからRGBに変換 27 x = x[:, :, :: -1] 28 x = np.clip(x, 0, 255).astype('uint8') 29 return x 30# 学習済みのVGG19ネットワークを読み込み、3つの画像に適応 31from keras import backend as K 32target_image = K.constant(preprocess_image(target_image_path)) 33style_reference_image = K.constant(preprocess_image(style_reference_image_path)) 34# 生成された画像を保持するプレースホルダ 35combination_image = K.placeholder((1, img_height, img_width, 3)) 36# 3つの画像を1つのテンソルにまとめる 37input_tensor = K.concatenate( 38 [target_image, style_reference_image, combination_image], 39 axis = 0 40) 41# 3つの画像からなるバッチを入力として使用するVGG19モデルを構築 42# この学習済みのImageNetの重みが読み込まれる 43model = vgg19.VGG19( 44 input_tensor = input_tensor, 45 weights = 'imagenet', 46 include_top = False 47) 48# コンテンツの損失関数 49def content_loss(base, combination): 50 return K.sum(K.square(combination - base)) 51# スタイルの損失関数 52def gram_matrix(x): 53 features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1))) 54 gram = K.dot(features, K.transpose(features)) 55 return gram 56def style_loss(style, combination): 57 S = gram_matrix(style) 58 C = gram_matrix(combination) 59 channels = 3 60 size = img_height * img_width 61 return K.sum(K.square(S - C)) / (4 * (channels ** 2) * (size ** 2)) 62# 全変動損失関数 63def total_varidation_loss(x): 64 a = K.square( 65 x[:, : img_height - 1, :img_width - 1, :] - 66 x[:, 1:, :img_width -1:, :] 67 ) 68 b = K.square( 69 x[:, : img_height - 1, :img_width - 1, :] - 70 x[:, : img_height - 1, 1:, :] 71 ) 72 return K.sum(K.pow(a + b, 1.25)) 73# 最小化の対象となる最終的な損失関数の定義 74# 層の名前をテンソルにマッピングするディクショナリ 75outputs_dict = dict([(layer.name, layer.output) for layer in model.layers]) 76# コンテンツの損失関数に利用する層の名前 77content_layer = 'block5_conv2' 78# スタイルの損失関数に利用する層の利用 79style_layers = [ 80 'block1_conv1', 81 'block2_conv1', 82 'block3_conv1', 83 'block4_conv1', 84 'block4_conv1', 85 'block5_conv1' 86] 87# 損失関数の加重平均の重み 88total_varidation_weight = 1e-4 89style_weight = 1 90content_weight = 0.025 91# すべてのコンポーネントをこのスカラー変数に追加することで、損失関数を定義 92loss = K.variable(0) 93# コンテンツの損失関数を追加 94layer_features = outputs_dict[content_layer] 95target_image_features = layer_features[0, :, :, :] 96combination_features = layer_features[2, :, :, :] 97loss = loss + content_weight * content_loss(target_image_features, combination_features) 98# 各ターゲット層のスタイルの損失関数を追加 99for layer_name in style_layers: 100 layer_features = outputs_dict[layer_name] 101 style_reference_features = layer_features[1, :, :, :] 102 combination_features = layer_features[2, :, :, :] 103 sl = style_loss(style_reference_features, combination_features) 104 loss += (style_weight / len(style_layers)) * sl 105loss += total_varidation_weight * total_varidation_loss(combination_image) 106# 勾配降下法のプロセスを定義 107# 損失関数をもとに、生成された画像の勾配を取得する 108grads = K.gradients(loss, combination_image)[0] 109# 現在の損失関数の値と勾配の値を取得するための関数 110fetch_loss_and_grads = K.function([combination_image], [loss, grads]) 111class Evaluator(object): 112 def __init__(self): 113 self.loss_value = None 114 self.grads_values = None 115 def loss(self, x): 116 assert self.loss_value is None 117 x = x.reshape((1, img_height, img_width, 3)) 118 outs = fetch_loss_and_grads([x]) 119 loss_value = outs[0] 120 grad_values = outs[1].flatten().astype('float64') 121 self.loss_value = loss_value 122 self.grad_values = grad_values 123 return self.loss_value 124 def grads(self, x): 125 assert self.loss_value is not None 126 grad_values = np.copy(self.grad_values) 127 self.loss_value = None 128 self.grad_values = None 129 return grad_values 130evaluator = Evaluator() 131# スタイル変換ループ 132from scipy.optimize import fmin_l_bfgs_b 133import imageio 134import time 135result_prefix = './StyleTransfer/style_transfer_result' 136iterations = 20 137# 初期状態(ターゲット画像) 138x = preprocess_image(target_image_path) 139# 画像を平坦化 140x = x.flatten() 141for i in range(iterations): 142 print('Start of iteration', i) 143 start_time = time.time() 144 x, min_val, info = fmin_l_bfgs_b( 145 evaluator.loss, 146 x, 147 fprime = evaluator.grads, 148 maxfun = 20 149 ) 150 print('Current loss value', min_val) 151 # 現在の画像を保存する 152 img = x.copy().reshape((img_height, img_width, 3)) 153 img = deprocess_image(img) 154 fname = result_prefix + '_at_iteration_%d.png' % i 155 imageio.imwrite(fname, img) 156 end_time = time.time() 157 print('Image save as', fname) 158 print('Iteration %d completed in %ds' % (i, end_time - start_time))

使用した画像

Elephant.jpg
Elephant.jpg
transfer_style_reference.jpg'
transfer_style_reference.jpg

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

OS:Windows10
Pythonのバージョン:Python 3.7.4
kerasのバージョン:2.3.1
tensorflowのバージョン:'1.15.0'
記述・実行:Jupyter Notebook
Anacondaを使ってPythonをインストールしました.

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

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

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

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

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

yymmt

2020/08/02 12:13

GPUが呼ばれているようですがグラフィックボードは何をお使いでしょうか?
coco_bauer

2020/08/02 14:09

『「imsaveモジュール」ではなく「imageioモジュール」にしました』という変更をした理由は? 「RunOptionsに'report_tensor_allocations_upon_oom'を追加すると、メモリ不足(oom [Out of Memory])が起きた時のアロケート済みのテンソルのリストが見られる」との助言がエラーメッセージに書かれていますが、やってみましたか?
Mr.AK

2020/08/02 17:47

yymmt 様、coco_bauer 様 ありがとうございます. メモリ不足とのことだったので画像の大きさを小さくすることでbatch_sizeを減らしてみたところ、何とか実行することができました!
guest

回答1

0

自己解決

メモリ消費量を減らすために「img_height = 400」の値を小さくしてみたところ、実行することができました.

投稿2020/08/02 17:57

Mr.AK

総合スコア5

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.49%

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

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

質問する

関連した質問