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

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

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

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

Python

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

Q&A

解決済

1回答

4334閲覧

TypeErrorとArgumentError

rich

総合スコア12

Python 3.x

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

Python

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

0グッド

0クリップ

投稿2017/08/21 11:03

編集2017/08/22 06:04

###前提・実現したいこと
現在、以下の書籍で勉強しています。
https://books.google.co.jp/books?id=egMlDwAAQBAJ&printsec=frontcover&hl=ja&source=gbs_ge_summary_r&cad=0#v=onepage&q&f=false

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

一度目に動かすと、 TypeError: expected str, bytes or os.PathLike object, not NoneType となり、二度目以降は ArgumentError: argument --image_dir: conflicting option string: --image_dir このようなエラーが出てしまいます。 追記 ArgumentError Traceback (most recent call last) <ipython-input-20-3948841d33b1> in <module>() 19 20 FLAGS = tf.app.flags.FLAGS ---> 21 tf.app.flags.DEFINE_string('image_dir', None, "学習画像のディレクトリ") 22 23 tf.app.flags.DEFINE_integer('batch_size', 128, "ミニバッチのサイズ") というようなエラーが出ています。 別のコードで、flags.pyというファイルで in DEFINE_string(flag_name, default_value, docstring) 78 docstring: A helpful message explaining the use of the flag. 79 """ ---> 80 _define_helper(flag_name, default_value, docstring, str) 81 82 n _define_helper(flag_name, default_value, docstring, flagtype) 63 default=default_value, 64 help=docstring, ---> 65 type=flagtype) 66 67 というエラーが出ています。 また、argparse.pyというファイルでも6つエラーが出ています。 これらはArgumentErrorです。

###該当のソースコード

Python

1 2import imghdr 3import math 4import os 5 6import numpy as np 7import tensorflow as tf 8from PIL import Image 9 10import util.current_time as current_time 11from srcnn.image_loader_vvv import load_image 12from srcnn.model import model915 13from srcnn.model import model915_svs 14from srcnn.model import model915_sigmoid 15from srcnn.model import model955_sigmoid 16from srcnn.model import model955_sigmoid_color 17from srcnn.model import model955_sigmoid_bn_color 18 19MODEL = model915_sigmoid 20 21FLAGS = tf.app.flags.FLAGS 22tf.app.flags.DEFINE_string('image_dir', None, "学習画像のディレクトリ") 23 24tf.app.flags.DEFINE_integer('batch_size', 128, "ミニバッチのサイズ") 25tf.app.flags.DEFINE_float('learning_rate', 0.001, "学習率") 26 27tf.app.flags.DEFINE_string('train_dir', './train_sr', 28 "学習結果を保存するディレクトリ") 29 30tf.app.flags.DEFINE_integer('scale', 2, "") 31 32tf.app.flags.DEFINE_boolean('log_device_placement', False, 33 "opが実行されるデバイスを表示するかを選択") 34tf.app.flags.DEFINE_integer('min_after_dequeue', 30000, 35 "dequeueをはじめるサンプル数") 36tf.app.flags.DEFINE_integer('num_threads', 16, "処理するスレッド数") 37 38tf.app.flags.DEFINE_integer('max_step', -1, "学習する最大ステップ数") 39 40 41def __loss(sr_images, ground_truth): 42 return tf.reduce_mean( 43 tf.squared_difference(sr_images, ground_truth)) 44 45 46def __init_optimizer(learning_rate): 47 opt = tf.train.AdamOptimizer(learning_rate) 48 return opt 49 50 51def __train(file_list, patches_count, train_dir): 52 checkpoint_path = os.path.join(train_dir, 'model.ckpt') 53 file_abort = os.path.join(train_dir, 'abort.now') 54 55 print('batch_size %d' % FLAGS.batch_size) 56 step_of_epoch = math.ceil(patches_count / FLAGS.batch_size) 57 print('step of epoch %d' % step_of_epoch) 58 59 images, ground_truths = load_image( 60 file_list, 61 MODEL.INPUT_SIZE, MODEL.OUTPUT_SIZE, 62 channels=MODEL.CHANNELS, 63 scale=FLAGS.scale, 64 batch_size=FLAGS.batch_size // 4) 65 66 capacity = FLAGS.min_after_dequeue + 4 * FLAGS.batch_size 67 68 lr_image_batch, ground_truth_batch = tf.train.shuffle_batch( 69 [images, ground_truths], 70 batch_size=FLAGS.batch_size, 71 capacity=capacity, 72 enqueue_many=True, 73 min_after_dequeue=FLAGS.min_after_dequeue, 74 num_threads=FLAGS.num_threads) 75 76 sr_images = MODEL.inference(lr_image_batch) 77 78 summary_images = tf.concat([ground_truth_batch, sr_images], axis=1) 79 tf.summary.image('images', summary_images, max_outputs=4) 80 81 loss = __loss(sr_images, ground_truth_batch) 82 tf.summary.scalar('total_loss', loss) 83 84 global_step = tf.Variable(0, trainable=False) 85 opt = __init_optimizer(FLAGS.learning_rate) 86 train_op = opt.minimize(loss, global_step=global_step) 87 88 config = tf.ConfigProto( 89 allow_soft_placement=True, 90 log_device_placement=FLAGS.log_device_placement) 91 92 saver = tf.train.Saver(tf.global_variables(), max_to_keep=100) 93 summary_op = tf.summary.merge_all() 94 95 coord = tf.train.Coordinator() 96 97 with tf.Session(config=config) as sess: 98 checkpoint = tf.train.get_checkpoint_state(train_dir) 99 if not (checkpoint and checkpoint.model_checkpoint_path): 100 sess.run(tf.global_variables_initializer()) 101 else: 102 saver.restore(sess, checkpoint.model_checkpoint_path) 103 104 threads = tf.train.start_queue_runners(sess=sess, coord=coord) 105 106 summary_writer = tf.summary.FileWriter(train_dir, sess.graph) 107 108 step = 0 109 110 try: 111 while not coord.should_stop(): 112 start = current_time.in_millis() 113 114 _, step, loss_value = sess.run( 115 [train_op, global_step, loss] 116 ) 117 118 assert not np.isnan(loss_value), \ 119 'Model diverged with loss = NaN' 120 121 elapsed = current_time.in_millis() - start 122 123 if step % 100 == 0: 124 print('Step: %d, Loss: %.6f, Time: %dms / step' % (step, loss_value, elapsed)) 125 126 if step % 100 == 0: 127 summary_str = sess.run(summary_op) 128 summary_writer.add_summary(summary_str, step) 129 130 if (step % 10000 == 0): 131 saver.save(sess, checkpoint_path, global_step=step) 132 if os.path.exists(file_abort): 133 print('abort file(%s) detected.' % file_abort) 134 break 135 136 if FLAGS.max_step > 0 and FLAGS.max_step <= step: 137 print('step limit %d reached' % FLAGS.max_step) 138 saver.save(sess, checkpoint_path, global_step=step) 139 break 140 141 except tf.errors.OutOfRangeError: 142 print('Done training -- epoch limit reached') 143 finally: 144 saver.save(sess, checkpoint_path, global_step=step) 145 coord.request_stop() 146 147 # Wait for threads to finish. 148 coord.join(threads) 149 150 151def __count_patches(image, patch_size): 152 horizontal = math.ceil(image.width / patch_size) 153 vertical = math.ceil(image.height / patch_size) 154 return horizontal * vertical 155 156 157def __check_size_and_count_patches(file_list, patch_size): 158 count = 0 159 result_list = [] 160 161 for file in file_list: 162 with Image.open(file) as image: 163 if image.height >= patch_size and image.width >= patch_size: 164 result_list.append(file) 165 count += __count_patches(image, patch_size) 166 else: 167 print('%s is dropped. %d:%d' % (file, image.height, image.width)) 168 169 return result_list, count 170 171 172def main(argv=None): 173 if not os.path.exists(FLAGS.train_dir): 174 os.makedirs(FLAGS.train_dir) 175 176 image_files = os.walk(FLAGS.image_dir) 177 178 file_list = [] 179 for dirpath, dirs, files in image_files: 180 png_files = list(filter(lambda f: f.lower().endswith('.jpg'), files)) 181 file_list.extend(list(map(lambda f: os.path.join(dirpath, f), png_files))) 182 183 file_list = list(filter(lambda f: imghdr.what(f) == 'jpeg', file_list)) 184 file_list, patches_count = __check_size_and_count_patches(file_list, MODEL.INPUT_SIZE) 185 186 print('%d, %d' % (len(file_list), patches_count)) 187 188 train_dir = os.path.join(FLAGS.train_dir, MODEL.NAME) 189 if not os.path.exists(train_dir): 190 os.makedirs(train_dir) 191 192 __train(file_list, patches_count, train_dir) 193 194 195if __name__ == '__main__': 196 tf.app.run() 197

tf.app.flags.DEFINE_string('image_dir', None, "学習画像のディレクトリ")
この場合、image_dirは学習させる画像のディレクトリということでしょうか?
自分のPC内の画像ディレクトリはどこにかけば良いのでしょうか?

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

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

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

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

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

退会済みユーザー

退会済みユーザー

2017/08/21 13:20

TypeError: expected str, bytes or os.PathLike object, not NoneTypeのエラーの時に、何行目でエラーが出たかありましたか?その数字があると皆さんの回答が得られやすいと思います。image_dirにはご察しの通りディレクトリ名が必要です。windowsなら"C:\pictures"みたいな感じです。
guest

回答1

0

自己解決

画像ディレクトリを追加して動かすことができました。
ArgumentErrorは2回以上実行すると起こってしまうエラーのようです。
ありがとうございました。

投稿2017/08/22 07:43

rich

総合スコア12

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問