2016-02-15 68 views
5

Tôi gặp phải lỗi trình giữ chỗ.TensorFlow: PlaceHolder lỗi khi sử dụng tf.merge_all_summaries()

Tôi không biết ý nghĩa của nó, bởi vì tôi đang lập bản đồ chính xác trên sess.run(..., {_y: y, _X: X}) ... Tôi cung cấp ở đây một MWe đầy đủ chức năng tái tạo các lỗi:

import tensorflow as tf 
import numpy as np 

def init_weights(shape): 
    return tf.Variable(tf.random_normal(shape, stddev=0.01)) 

class NeuralNet: 
    def __init__(self, hidden): 
     self.hidden = hidden 

    def __del__(self): 
     self.sess.close() 

    def fit(self, X, y): 
     _X = tf.placeholder('float', [None, None]) 
     _y = tf.placeholder('float', [None, 1]) 

     w0 = init_weights([X.shape[1], self.hidden]) 
     b0 = tf.Variable(tf.zeros([self.hidden])) 
     w1 = init_weights([self.hidden, 1]) 
     b1 = tf.Variable(tf.zeros([1])) 

     self.sess = tf.Session() 
     self.sess.run(tf.initialize_all_variables()) 

     h = tf.nn.sigmoid(tf.matmul(_X, w0) + b0) 
     self.yp = tf.nn.sigmoid(tf.matmul(h, w1) + b1) 

     C = tf.reduce_mean(tf.square(self.yp - y)) 
     o = tf.train.GradientDescentOptimizer(0.5).minimize(C) 

     correct = tf.equal(tf.argmax(_y, 1), tf.argmax(self.yp, 1)) 
     accuracy = tf.reduce_mean(tf.cast(correct, "float")) 
     tf.scalar_summary("accuracy", accuracy) 
     tf.scalar_summary("loss", C) 

     merged = tf.merge_all_summaries() 
     import shutil 
     shutil.rmtree('logs') 
     writer = tf.train.SummaryWriter('logs', self.sess.graph_def) 

     for i in xrange(1000+1): 
      if i % 100 == 0: 
       res = self.sess.run([o, merged], feed_dict={_X: X, _y: y}) 
      else: 
       self.sess.run(o, feed_dict={_X: X, _y: y}) 
     return self 

    def predict(self, X): 
     yp = self.sess.run(self.yp, feed_dict={_X: X}) 
     return (yp >= 0.5).astype(int) 


X = np.array([ [0,0,1],[0,1,1],[1,0,1],[1,1,1]]) 
y = np.array([[0],[1],[1],[0]]]) 

m = NeuralNet(10) 
m.fit(X, y) 
yp = m.predict(X)[:, 0] 
print accuracy_score(y, yp) 

Lỗi:

I tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 8 
I tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 8 
0.847222222222 
W tensorflow/core/common_runtime/executor.cc:1076] 0x2340f40 Compute status: Invalid argument: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float 
    [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 
W tensorflow/core/common_runtime/executor.cc:1076] 0x2340f40 Compute status: Invalid argument: You must feed a value for placeholder tensor 'Placeholder' with dtype float 
    [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 
Traceback (most recent call last): 
    File "neuralnet.py", line 64, in <module> 
    m.fit(X[tr], y[tr, np.newaxis]) 
    File "neuralnet.py", line 44, in fit 
    res = self.sess.run([o, merged], feed_dict={self._X: X, _y: y}) 
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 368, in run 
    results = self._do_run(target_list, unique_fetch_targets, feed_dict_string) 
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 444, in _do_run 
    e.code) 
tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float 
    [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 
Caused by op u'Placeholder_1', defined at: 
    File "neuralnet.py", line 64, in <module> 
    m.fit(X[tr], y[tr, np.newaxis]) 
    File "neuralnet.py", line 16, in fit 
    _y = tf.placeholder('float', [None, 1]) 
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.py", line 673, in placeholder 
    name=name) 
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 463, in _placeholder 
    name=name) 
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 664, in apply_op 
    op_def=op_def) 
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1834, in create_op 
    original_op=self._default_original_op, op_def=op_def) 
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1043, in __init__ 
    self._traceback = _extract_stack() 

Nếu tôi xóa tf.merge_all_summaries() hoặc xóa merged khỏi self.sess.run([o, merged], ...) thì nó sẽ hoạt động bình thường.

này trông tương tự như bài này: Error when computing summaries in TensorFlow Tuy nhiên, tôi không sử dụng ipython ...

+0

có thể trùng lặp của [Lỗi khi tính toán tóm tắt trong TensorFlow] (http://stackoverflow.com/questions/35114376/error-when-computing-summaries-in-tensorflow) –

+0

@YaroslavBulatov Tôi đã tìm kiếm và tìm thấy bài đăng đó. Nó trông tương tự. Vấn đề là lỗi của anh ta chỉ có thể tái tạo trong IPython. Tôi không sử dụng IPython. Tôi đang sử dụng "bình thường" Python ... –

+0

Bạn backtrace nói lỗi xảy ra trong "sess.run ([o, sáp nhập], feed_dict = {self._X: X, _y: y})" ... nhưng không có dòng trong mã bạn đã đăng. –

Trả lời

16

Chức năng tf.merge_all_summaries() là thuận tiện, nhưng cũng hơi nguy hiểm: nó kết hợp tất cả tóm tắt trong đồ thị mặc định, bao gồm bất kỳ bản tóm tắt nào từ trước đó — dường như chưa được kết nối — lời gọi mã cũng đã thêm các nút tóm tắt vào biểu đồ mặc định. Nếu các nút tóm tắt cũ phụ thuộc vào trình giữ chỗ cũ, bạn sẽ nhận được các lỗi giống như phần bạn đã hiển thị trong câu hỏi của mình (và cũng giống như previousquestions).

Có hai cách giải quyết độc lập:

  1. Đảm bảo rằng bạn thu thập một cách rõ ràng tóm tắt mà bạn muốn tính toán. Đây là đơn giản như sử dụng rõ ràng tf.merge_summary() op trong ví dụ của bạn:

    accuracy_summary = tf.scalar_summary("accuracy", accuracy) 
    loss_summary = tf.scalar_summary("loss", C) 
    
    merged = tf.merge_summary([accuracy_summary, loss_summary]) 
    
  2. Đảm bảo rằng mỗi khi bạn tạo một bộ mới của bản tóm tắt, bạn làm như vậy trong một đồ thị mới. Phong cách khuyến cáo là sử dụng một đồ thị mặc định rõ ràng:

    with tf.Graph().as_default(): 
        # Build model and create session in this scope. 
        # 
        # Only summary nodes created in this scope will be returned by a call to 
        # `tf.merge_all_summaries()` 
    

    Ngoài ra, nếu bạn đang sử dụng phiên bản mã nguồn mở mới nhất của TensorFlow (hoặc 0.7.0 phát hành sắp xuất bản), bạn có thể gọi tf.reset_default_graph() để thiết lập lại nhà nước của biểu đồ và xóa bất kỳ nút tóm tắt cũ nào.

+0

# 1 là vấn đề thực sự! Bây giờ tất cả đều có ý nghĩa, cảm ơn! –

+0

Bạn là sếp! Tôi đã bị mất trong vài giờ qua! Cảm ơn rất nhiều! – Gooshan

+0

Bạn nói đúng về phần "nguy hiểm". TF có rất nhiều hành vi tiềm ẩn có ý định tốt nhưng cuối cùng gây ra sự nhầm lẫn và lỗi cho những người không biết về chúng. –

Các vấn đề liên quan