tensorflow tf.train.batch之資料批量讀取

來源:互聯網
上載者:User

在進行大量資料訓練神經網路的時候,可能需要批量讀取資料。於是參考了這篇博文的代碼,結果探索資料一直批量迴圈輸出,不會在資料的末尾自動停止。然後發現這篇博文說slice_input_producer()這個函數有一個形參num_epochs,通過設定它的值就可以控制全部資料迴圈輸出幾次。於是我設定之後出現以下的報錯:

tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value input_producer/input_producer/limit_epochs/epochs         [[Node: input_producer/input_producer/limit_epochs/CountUpTo = CountUpTo[T=DT_INT64, _class=["loc:@input_producer/input_producer/limit_epochs/epochs"], limit=2, _device="/job:localhost/replica:0/task:0/cpu:0"](input_producer/input_producer/limit_epochs/epochs)]]

找了好久,都不知道為什麼會錯,於是只好去看看slice_input_producer()函數的源碼,結果在源碼中發現作者說這個num_epochs如果不是空的話,就是一個局部變數,需要先調用global_variables_initializer()函數初始化。於是我調用了之後,一切就正常了,特此記錄下來,希望其他人遇到的時候能夠及時找到原因。哈哈,這是筆者第一次通過閱讀源碼解決了問題,心情還是有點小激動。啊啊,扯遠了,上最終成功的代碼:

import pandas as pdimport numpy as npimport tensorflow as tfdef generate_data():    num = 25    label = np.asarray(range(0, num))    images = np.random.random([num, 5])    print('label size :{}, image size {}'.format(label.shape, images.shape))    return images,labeldef get_batch_data():    label, images = generate_data()    input_queue = tf.train.slice_input_producer([images, label], shuffle=False,num_epochs=2)    image_batch, label_batch = tf.train.batch(input_queue, batch_size=5, num_threads=1, capacity=64,allow_smaller_final_batch=False)    return image_batch,label_batchimages,label = get_batch_data()sess = tf.Session()sess.run(tf.global_variables_initializer())sess.run(tf.local_variables_initializer())#就是這一行coord = tf.train.Coordinator()threads = tf.train.start_queue_runners(sess,coord)try:    while not coord.should_stop():        i,l = sess.run([images,label])        print(i)        print(l)except tf.errors.OutOfRangeError:    print('Done training')finally:    coord.request_stop()coord.join(threads)sess.close()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.