2017-12-23 16 views
0

데이터가 tfrecord 파일에 저장되었습니다. 1000 개의 샘플과 2 개의 피쳐 (하나는 다른 출력을 입력)가 있습니다. 입력은 모양 [1,20]과 출력 [1,10]입니다. 그들은 모두 평평하게 배열 된 배열로부터 만들어졌습니다. 나는 그들을 네트워크에서 훈련시키기 위해 사용할 수 있도록 배치를 만들려고 노력하고있다. 그러나 나는 그 방법을 알 수 없다.tensorflow에서 교육 네트워크 용 TFrecord에서 일괄 처리를 만드는 방법은 무엇입니까?

이이 내가로부터 데이터를 얻고 파일입니다 네트워크

learning_rate = 0.01 
epochs = 2 
batch_size = 200 #total 5 batches 
dataSize = 1000 

dataset = rd.getData() 

x = tf.placeholder(shape=(None,20), dtype=tf.float32) 
y = tf.placeholder(shape=(None,10), dtype=tf.float32) 

w1 = tf.Variable(tf.random_normal([20, 20], stddev=0.03)) 
w2 = tf.Variable(tf.random_normal([20, 20], stddev=0.03)) 
w3 = tf.Variable(tf.random_normal([20, 20], stddev=0.03)) 
w4 = tf.Variable(tf.random_normal([20, 20], stddev=0.03)) 
w5 = tf.Variable(tf.random_normal([20, 10], stddev=0.03)) 

b1 = tf.Variable(tf.random_normal([20])) 
b2 = tf.Variable(tf.random_normal([20])) 
b3 = tf.Variable(tf.random_normal([20])) 
b4 = tf.Variable(tf.random_normal([20])) 
b5 = tf.Variable(tf.random_normal([10])) 

out1 = tf.add(tf.matmul(x, w1), b1) 
out1 = tf.tanh(out1) 

out2 = tf.add(tf.matmul(out1, w2), b2) 
out2 = tf.tanh(out2) 

out3 = tf.add(tf.matmul(out2, w3), b3) 
out3 = tf.tanh(out3) 

out4 = tf.add(tf.matmul(out3, w4), b4) 
out4 = tf.tanh(out4) 

out5 = tf.add(tf.matmul(out4, w5), b5) 
finalOut = tf.tanh(out5) 

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=finalOut)) 


optimiser = tf.train.RMSPropOptimizer(learning_rate=learning_rate).minimize(cost) 

# finally setup the initialisation operator 
init_op = tf.global_variables_initializer() 


with tf.Session() as sess: 
    # initialise the variables 
    sess.run(init_op) 
    total_batch = int(dataSize/batch_size) 
    for epoch in range(epochs): 

    iterator = dataset.make_one_shot_iterator() 
    avg_cost = 0 

    for i in range(total_batch): 

     #create batch 
     batch_y = [] 
     batch_x = [] 
     for counter in range(0,batch_size): 
     uv, z = iterator.get_next() 
     batch_x.append(uv) 
     batch_y.append(z) 

     _, c = sess.run([optimiser, cost], 
        feed_dict={x: batch_x, y: batch_y}) 
     avg_cost += c/total_batch 
     print("Epoch:", (epoch + 1), "cost =", "{:.3f}".format(avg_cost)) 

훈련에 대한 내 코드입니다.

def decode(serialized_example): 

    features = tf.parse_single_example(
    serialized_example, 
    features={'uv': tf.FixedLenFeature([1,20], tf.float32), 
      'z': tf.FixedLenFeature([1,10], tf.float32)}) 

    return features['uv'], features['z'] 


def getData(): 

    filename = ["train.tfrecords"] 
    dataset = tf.data.TFRecordDataset(filename).map(decode) 
    return dataset 

오류 :

Traceback (most recent call last): 
File "network.py", line 102, in <module> 
feed_dict={x: batch_x, y: batch_y}) 
    File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 889, in run 
run_metadata_ptr) 
    File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1089, in _run 
np_val = np.asarray(subfeed_val, dtype=subfeed_dtype) 
    File "C:\Users\User\AppData\Roaming\Python\Python36\site-packages\numpy\core\numeric.py", line 531, in asarray 
return array(a, dtype, copy=False, order=order) 
ValueError: setting an array element with a sequence. 

다른 질문보고 후, 나는 아마 내 배치가 ndarray 또는 뭔가해야한다 생각? 그러나 나는 그 형태로 나의 데이터 세트를 얻는 방법을 알지 못한다. 나는 반복자없이 데이터를 사용하는 방법을 모색한다. 어떤 지침이 좋을 것입니다! 감사합니다

답변

0

도움이되는지 다음과 같이 시도해보십시오.

  1. tf.parse_single_example은 배치 차원을받지 않습니다. 따라서,

    features = tf.parse_single_example(
        serialized_example, 
        features={'uv': tf.FixedLenFeature([20], tf.float32), 
         'z': tf.FixedLenFeature([10], tf.float32)}) 
    
  2. Simple Batching section of TensorFlow Guide on Dataset API에서, 당신은 print(sess.run(next_element)) 3 번 실행되지만 next_element 한 번만 선언 된 것을 발견 할 것이다. 마찬가지로 코드에서 dataset.make_one_shot_iterator()iterator.get_next()을 for-loop에서 실행할 필요가 없습니다. 데이터 집합 선언은 처음부터 쉽게 이해할 수 있도록 getData() 안에 넣을 수 있습니다.

  3. 데이터를 일괄하여 형성 할 수있다

    # read file 
    dataset = tf.data.TFRecordDataset(filename) 
    # parse each instance 
    dataset = dataset.map(your_parser_fun, num_parallel_calls=num_threads) 
    # preprocessing, e.g. scale to range [0, 1] 
    dataset = dataset.map(some_preprocessing_fun) 
    # shuffle 
    dataset = dataset.shuffle(buffer_size) 
    # form batch and epoch 
    dataset = dataset.batch(batch_size) 
    dataset = dataset.repeat(num_epoch) 
    iterator = dataset.make_one_shot_iterator() 
    # get a batch 
    x_batch, y_batch = self.iterator.get_next() 
    
    # do calculations 
    ... 
    
  4. 체크 Processing multiple epochs section는 피 루프 에포크 설정의 일례를 표시.