在進(jìn)行大量數(shù)據(jù)訓(xùn)練神經(jīng)網(wǎng)絡(luò)的時(shí)候,可能需要批量讀取數(shù)據(jù)。于是參考了這篇文章的代碼,結(jié)果發(fā)現(xiàn)數(shù)據(jù)一直批量循環(huán)輸出,不會(huì)在數(shù)據(jù)的末尾自動(dòng)停止。
然后發(fā)現(xiàn)這篇博文說(shuō)slice_input_producer()這個(gè)函數(shù)有一個(gè)形參num_epochs,通過(guò)設(shè)置它的值就可以控制全部數(shù)據(jù)循環(huán)輸出幾次。
于是我設(shè)置之后出現(xiàn)以下的報(bào)錯(cuò):
1
2
3
|
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)]] |
找了好久,都不知道為什么會(huì)錯(cuò),于是只好去看看slice_input_producer()函數(shù)的源碼,結(jié)果在源碼中發(fā)現(xiàn)作者說(shuō)這個(gè)num_epochs如果不是空的話,就是一個(gè)局部變量,需要先調(diào)用global_variables_initializer()函數(shù)初始化。
于是我調(diào)用了之后,一切就正常了,特此記錄下來(lái),希望其他人遇到的時(shí)候能夠及時(shí)找到原因。
哈哈,這是筆者第一次通過(guò)閱讀源碼解決了問(wèn)題,心情還是有點(diǎn)小激動(dòng)。啊啊,扯遠(yuǎn)了,上最終成功的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
import pandas as pd import numpy as np import tensorflow as tf def 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,label def 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_batch images,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() |
以上這篇tensorflow tf.train.batch之?dāng)?shù)據(jù)批量讀取方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/liweibin1994/article/details/78306417