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

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

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

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

Q&A

解決済

2回答

3799閲覧

AttributeError: 'Cifar10Reader' object has no attribute 'bytestream' のエラー

退会済みユーザー

退会済みユーザー

総合スコア0

Python 3.x

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

0グッド

0クリップ

投稿2017/04/22 08:29

AttributeError: 'Cifar10Reader' object has no attribute 'bytestream' とエラーが出ました。
現在、以下のサイトを見て勉強しています。
http://www.buildinsider.net/small/booktensorflow/0204

以下のコードを

# coding: UTF-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import tensorflow as tf import model as model import numpy as np from reader import Cifar10Reader FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_integer('epoch', 30, "訓練するEpoch数") tf.app.flags.DEFINE_string('data_dir', './data/', "訓練データのディレクトリ") tf.app.flags.DEFINE_string('checkpoint_dir', './checkpoints/', "チェックポイントを保存するディレクトリ") tf.app.flags.DEFINE_string('test_data', None, "テストデータのパス") def _loss(logits, label): labels = tf.cast(label, tf.int64) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels,name='cross_entropy_per_example') cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy') return cross_entropy_mean def _train(total_loss, global_step): opt = tf.train.GradientDescentOptimizer(learning_rate=0.001) grads = opt.compute_gradients(total_loss) train_op = opt.apply_gradients(grads, global_step=global_step) return train_op filenames = [ os.path.join( FLAGS.data_dir, 'data_batch_%d.bin' % i) for i in range(1, 6) ] def main(argv=None): global_step = tf.Variable(0,trainable=False) train_placeholder = tf.placeholder(tf.float32, shape=[32, 32, 3], name='input_image') label_placeholder = tf.placeholder(tf.int32,shape=[1],name='label') # (width, height, depth) -> (batch, width, height, depth) image_node = tf.expand_dims(train_placeholder, 0) logits = model.inference(image_node) total_loss = _loss(logits,label_placeholder) train_op = _train(total_loss,global_step) top_k_op = tf.nn.in_top_k(logits,label_placeholder,1) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) total_duration = 0 for epoch in range(1, FLAGS.epoch + 1): start_time = time.time() for file_index in range(5): print('Epoch %d: %s' % (epoch, filenames[file_index])) reader = Cifar10Reader(filenames[file_index]) for index in range(10000): image = reader.read(index) logits_value = sess.run([logits], feed_dict={ train_placeholder: image.byte_array }) _,loss_value = sess.run([train_op,total_loss], feed_dict={ train_placeholder: image.byte_array, label_placeholder: image.label } ) if index % 1000 == 0: print('[%d]: %r' % (image.label, logits_value)) assert not np.isnan(loss_value), \ 'Model diverged with loss = NaN' reader.close() duration = time.time() - start_time total_duration += duration prediction = _eval(sess,top_k_op,train_placeholder,label_placeholder) print('epoch %d duration = %d sec' % (epoch, duration)) tf.train.SummaryWriter(FLAGS.checkpoint_dir, sess.graph) print('Total duration = %d sec' % total_duration) def _eval(sess,top_k_op,train_placeholder,label_placeholder): if not FLAGS.test_data: return np.nan image_reader = Cifar10Reader(FLAGS.test_data) true_count = 0 for index in range(10000): image = image_reader.read(index) predictions = sess.run([top_k_op], feed_dict={ input_image: image.image, label_placeholder:image.label } ) true_count += np.sum(predictions) image_reader.close() if __name__ == '__main__': tf.app.run()

python inference.py --file ./cifar-10-batches-bin 2
と実行すると(./cifar-10-batches-bin 2は学習させたいファイルを置いてある場所)
./data/data_batch_1.bin is not exist
Traceback (most recent call last):
File "inference.py", line 120, in <module>
tf.app.run()
File "/Users/XXX/anaconda/envs/py36/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 44, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
File "inference.py", line 71, in main
image = reader.read(index)
File "/Users/XXX/Desktop/cifar/reader.py", line 42, in read
self.bytestream.seek(record_bytes * index,0)
AttributeError: 'Cifar10Reader' object has no attribute 'bytestream'
とエラーが出ました。
AttributeErrorで'Cifar10Reader'が'bytestream'という属性を持っていないことはわかるのですが、どこを直せば良いのでしょうか?

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

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

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

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

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

guest

回答2

0

ベストアンサー

./data/data_batch_1.bin is not exist

./data/data_batch_1.binファイルが存在しません。

class Cifar10Readerの__init__メソッド(コンストラクタ)内でファイルが存在しない時にprint文の表示後にreturnでコンストラクタを抜けてます。
よって(ファイルが存在しない時は)self.bytestreamが定義されません。


以下はコメント欄の追加質問への回答です。

「プログラムは思った通りには動かない。書いたとおりに動くのだ」と良く云われてます。
よって、質問者がそう動くようにプログラムを書いたのです。
具体的には、質問者のコメントの

filenames = [
os.path.join(
FLAGS.data_dir, 'data_batch_%d.bin' % i) for i in range(1, 6)
]

os.path.join でファイルパスを結合してます。
結合する対象は
1,変数:FLAGS.data_dir
2,data_batch_1.bin ~ data_batch_5.bin です。

変数:FLAGS.data_dirの定義は質問者が質問文に貼ったコードの17行目で

tf.app.flags.DEFINE_string('data_dir', './data/', "訓練データのディレクトリ")

よって結合文字列は ./data/ と data_batch_1.bin ~ data_batch_5.bin になります。

提案)IDEのpychramのフリー版をいれてデバックで値を確認してみてはどーでしょうか。

投稿2017/04/22 17:03

編集2017/04/23 08:31
umyu

総合スコア5846

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

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

退会済みユーザー

退会済みユーザー

2017/04/23 00:54

ありがとうございます。質問のコードに filenames = [ os.path.join( FLAGS.data_dir, 'data_batch_%d.bin' % i) for i in range(1, 6) ] という部分があるのですが、./data/というディレクトリ指定をしておらず、なぜ./data/のディレクトリ指定がついてしまうのでしょうか?data_batch_1.binはcifar-10-batches-bin-2 というフォルダの中にあるので、指定を変えたいのですが
umyu

2017/04/23 03:41

お願い)追加質問はコメント欄ではなくて、質問文に追記してくださいな。 基本的にはサンプルは自分でコードについて理解できるまでは、 フォルダ構成などを勝手に変えるべきではありません。
退会済みユーザー

退会済みユーザー

2017/06/18 16:40

umyuさんのおっしゃるように、 tf.app.flags.DEFINE_string('data_dir', './data/', "訓練データのディレクトリ") の'./data/'の部分を'./cifar-10-batches-bin-2/'に変更すれば完了ですよ。(解決済みみたいですが僕みたいな素人さんのため) ちなみに、僕の時はデータを解凍したときに.binが無くなっていたので filenames = [ os.path.join( FLAGS.data_dir, 'data_batch_%d.bin' % i) for i in range(1, 6) ] の部分も'data_batch_%d.bin'→'data_batch_%d' にしないといけませんでしたが
guest

0

Cifar10Readerbytestreamという属性を追加すればよいかと思います。

参考:TensorFlowでデータの読み込み ― 画像を分類するCIFAR-10の基礎 読み込みと構造変更

投稿2017/04/22 09:00

can110

総合スコア38262

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

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

退会済みユーザー

退会済みユーザー

2017/04/22 09:33

ありがとうございます。 class Cifar10Reader(object): def __init__(self,filename): if not os.path.exists(filename): print(filename + ' is not exist') return self.bytestream = open(filename,mode="rb") def close(self): if not self.bytestream: self.bytestream.close() def read(self,index): result = Cifar10Record() label_bytes = 1 image_bytes = result.height * result.width * result.depth record_bytes = label_bytes + image_bytes self.bytestream.seek(record_bytes * index,0) result.set_label(self.bytestream.read(label_bytes)) result.set_image(self.bytestream.read(image_bytes)) return result print(self.bytestream) とreader.pyに記述しているのですが、これだと違うのでしょうか?
can110

2017/04/22 15:19

細かく確認していませんが、Cifar10Readerクラスにbytestream属性は追加されていますでしょうか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問