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

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

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

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

YOLO

YOLOとは、画像検出および認識用ニューラルネットワークです。CベースのDarknetというフレームワークを用いて、画像や動画からオブジェクトを検出。リアルタイムでそれが何になるのかを認識し、分類することができます。

Python 3.x

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

Windows

Windowsは、マイクロソフト社が開発したオペレーティングシステムです。当初は、MS-DOSに変わるOSとして開発されました。 GUIを採用し、主にインテル系のCPUを搭載したコンピューターで動作します。Windows系OSのシェアは、90%を超えるといわれています。 パソコン用以外に、POSシステムやスマートフォンなどの携帯端末用、サーバ用のOSもあります。

Q&A

解決済

1回答

365閲覧

Using Theano backend.のTheanoをtensorflowに変更したい

tenki3

総合スコア3

Anaconda

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

YOLO

YOLOとは、画像検出および認識用ニューラルネットワークです。CベースのDarknetというフレームワークを用いて、画像や動画からオブジェクトを検出。リアルタイムでそれが何になるのかを認識し、分類することができます。

Python 3.x

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

Windows

Windowsは、マイクロソフト社が開発したオペレーティングシステムです。当初は、MS-DOSに変わるOSとして開発されました。 GUIを採用し、主にインテル系のCPUを搭載したコンピューターで動作します。Windows系OSのシェアは、90%を超えるといわれています。 パソコン用以外に、POSシステムやスマートフォンなどの携帯端末用、サーバ用のOSもあります。

0グッド

0クリップ

投稿2020/09/23 07:36

前提・実現したいこと

リンク内容
上記の記事を参考に、windows10でyolo3を使って独自学習を行おうとしました。anacondaの仮想環境で進めています。そしてtrain.pyを実行したところ、下記のエラーが発生しました。

調べたところ、anacondaだとバックエンドがtensorflowからTheanoに上書きされてしまい、それが原因かと思われます。
以下3つの記事を参考にしました。
リンク内容
リンク内容
リンク内容

しかし、windows10で.batの変更方法や無理やり作る方法などのやり方がわからず、ここからどう対応すればよいでしょうか?

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

Using Theano backend. Traceback (most recent call last): File "train.py", line 195, in <module> _main() File "train.py", line 35, in _main freeze_body=2, weights_path='model_data/yolo_weights.h5') # make sure you know what you freeze File "train.py", line 113, in create_model K.clear_session() # get a new session AttributeError: module 'keras.backend' has no attribute 'clear_session'

該当のソースコード

anaconda promptで実行

python

1python train.py 2""" 3Retrain the YOLO model for your own dataset. 4""" 5 6import numpy as np 7import keras.backend as K 8from keras.layers import Input, Lambda 9from keras.models import Model 10from keras.optimizers import Adam 11from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping 12 13from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss 14from yolo3.utils import get_random_data 15import sys 16 17def _main(): 18 annotation_path = 'model_data/2007_train.txt' 19 log_dir = 'logs/000/' 20 classes_path = 'model_data/voc_classes.txt' 21 anchors_path = 'model_data/yolo_anchors.txt' 22 class_names = get_classes(classes_path) 23 num_classes = len(class_names) 24 anchors = get_anchors(anchors_path) 25 26 input_shape = (320,320) # multiple of 32, hw 27 if len(sys.argv) > 1: 28 input_shape = (int(sys.argv[1]),int(sys.argv[1])) 29 30 is_tiny_version = len(anchors)==6 # default setting 31 if is_tiny_version: 32 model = create_tiny_model(input_shape, anchors, num_classes, 33 freeze_body=2, weights_path='model_data/tiny_yolo_weights.h5') 34 else: 35 model = create_model(input_shape, anchors, num_classes, 36 freeze_body=2, weights_path='model_data/yolo_weights.h5') # make sure you know what you freeze 37 38 logging = TensorBoard(log_dir=log_dir) 39 checkpoint = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5', 40 monitor='val_loss', save_weights_only=True, save_best_only=True, period=3) 41 reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1) 42 early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1) 43 44 val_split = 0.1 45 with open(annotation_path) as f: 46 lines = f.readlines() 47 np.random.seed(10101) 48 np.random.shuffle(lines) 49 np.random.seed(None) 50 num_val = int(len(lines)*val_split) 51 num_train = len(lines) - num_val 52 53 # Train with frozen layers first, to get a stable loss. 54 # Adjust num epochs to your dataset. This step is enough to obtain a not bad model. 55 if True: 56 model.compile(optimizer=Adam(lr=1e-3), loss={ 57 # use custom yolo_loss Lambda layer. 58 'yolo_loss': lambda y_true, y_pred: y_pred}) 59 60 batch_size = 32 61 if len(sys.argv) > 2: 62 batch_size = int(sys.argv[2]) 63 64 print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) 65 model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes), 66 steps_per_epoch=max(1, num_train//batch_size), 67 validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes), 68 validation_steps=max(1, num_val//batch_size), 69 epochs=50, 70 initial_epoch=0, 71 callbacks=[logging, checkpoint]) 72 model.save_weights(log_dir + 'trained_weights_stage_1.h5') 73 74 # Unfreeze and continue training, to fine-tune. 75 # Train longer if the result is not good. 76 if True: 77 for i in range(len(model.layers)): 78 model.layers[i].trainable = True 79 model.compile(optimizer=Adam(lr=1e-4), loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change 80 print('Unfreeze all of the layers.') 81 82 batch_size = 32 # note that more GPU memory is required after unfreezing the body 83 print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) 84 model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes), 85 steps_per_epoch=max(1, num_train//batch_size), 86 validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes), 87 validation_steps=max(1, num_val//batch_size), 88 epochs=100, 89 initial_epoch=50, 90 callbacks=[logging, checkpoint, reduce_lr, early_stopping]) 91 model.save_weights(log_dir + 'trained_weights_final.h5') 92 93 # Further training if needed. 94 95 96def get_classes(classes_path): 97 '''loads the classes''' 98 with open(classes_path) as f: 99 class_names = f.readlines() 100 class_names = [c.strip() for c in class_names] 101 return class_names 102 103def get_anchors(anchors_path): 104 '''loads the anchors from a file''' 105 with open(anchors_path) as f: 106 anchors = f.readline() 107 anchors = [float(x) for x in anchors.split(',')] 108 return np.array(anchors).reshape(-1, 2) 109 110 111def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2, 112 weights_path='model_data/yolo_weights.h5'): 113 '''create the training model''' 114 K.clear_session() # get a new session 115 image_input = Input(shape=(None, None, 3)) 116 h, w = input_shape 117 num_anchors = len(anchors) 118 119 y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \ 120 num_anchors//3, num_classes+5)) for l in range(3)] 121 122 model_body = yolo_body(image_input, num_anchors//3, num_classes) 123 print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes)) 124 125 if load_pretrained: 126 model_body.load_weights(weights_path, by_name=True, skip_mismatch=True) 127 print('Load weights {}.'.format(weights_path)) 128 if freeze_body in [1, 2]: 129 # Freeze darknet53 body or freeze all but 3 output layers. 130 num = (185, len(model_body.layers)-3)[freeze_body-1] 131 for i in range(num): model_body.layers[i].trainable = False 132 print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers))) 133 134 model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss', 135 arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})( 136 [*model_body.output, *y_true]) 137 model = Model([model_body.input, *y_true], model_loss) 138 139 return model 140 141def create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2, 142 weights_path='model_data/tiny_yolo_weights.h5'): 143 '''create the training model, for Tiny YOLOv3''' 144 K.clear_session() # get a new session 145 image_input = Input(shape=(None, None, 3)) 146 h, w = input_shape 147 num_anchors = len(anchors) 148 149 y_true = [Input(shape=(h//{0:32, 1:16}[l], w//{0:32, 1:16}[l], \ 150 num_anchors//2, num_classes+5)) for l in range(2)] 151 152 model_body = tiny_yolo_body(image_input, num_anchors//2, num_classes) 153 print('Create Tiny YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes)) 154 155 if load_pretrained: 156 model_body.load_weights(weights_path, by_name=True, skip_mismatch=True) 157 print('Load weights {}.'.format(weights_path)) 158 if freeze_body in [1, 2]: 159 # Freeze the darknet body or freeze all but 2 output layers. 160 num = (20, len(model_body.layers)-2)[freeze_body-1] 161 for i in range(num): model_body.layers[i].trainable = False 162 print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers))) 163 164 model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss', 165 arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.7})( 166 [*model_body.output, *y_true]) 167 model = Model([model_body.input, *y_true], model_loss) 168 169 return model 170 171def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes): 172 '''data generator for fit_generator''' 173 n = len(annotation_lines) 174 i = 0 175 while True: 176 image_data = [] 177 box_data = [] 178 for b in range(batch_size): 179 if i==0: 180 np.random.shuffle(annotation_lines) 181 image, box = get_random_data(annotation_lines[i], input_shape, random=True) 182 image_data.append(image) 183 box_data.append(box) 184 i = (i+1) % n 185 image_data = np.array(image_data) 186 box_data = np.array(box_data) 187 y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes) 188 yield [image_data, *y_true], np.zeros(batch_size) 189 190def data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes): 191 n = len(annotation_lines) 192 if n==0 or batch_size<=0: return None 193 return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes) 194 195if __name__ == '__main__': 196 _main() 197 198

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

windows10
anaconda
python=3.6.9
tensorflow==1.6.0
Keras==2.1.5

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

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

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

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

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

guest

回答1

0

自己解決

.batを左クリックの編集で開いてtensorflowに書き換えることができました。

投稿2020/09/23 10:12

tenki3

総合スコア3

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.49%

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

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

質問する

関連した質問