2017-07-17 26 views
0

我寫了一個簡單的代碼來嘗試Tensorflow彙總功能。代碼如下。在Tensorflow v1.2.1中使用匯總時InvalidArgumentError

import tensorflow as tf 
import numpy as np 

graph = tf.Graph() 


with graph.as_default(): 
    x = tf.placeholder(tf.float32, [1, 2], name='x') 
    W = tf.ones([2, 1], tf.float32, name='W') 
    b = tf.constant([1.5], dtype=tf.float32, shape=(1, 1), name='bias') 
    y_ = tf.add(tf.matmul(x, W, name='mul'), b, name='add') 
tf.summary.scalar('y', y_) 

with tf.Session(graph=graph) as session: 
    merged = tf.summary.merge_all() 
    fw = tf.summary.FileWriter("/tmp/tensorflow/logs", graph=graph) 

    tf.global_variables_initializer().run() 
    x_var = np.array([1., 1.], np.float32).reshape([1, 2]) 
    print(x_var) 
    summary, y = session.run([merged, y_], feed_dict={x: x_var}) 
    fw.add_summary(summary, 0) 
    print(y) 

    fw.close() 

基本上,它試圖實施y=Wx + b

該代碼的作品,如果我刪除所有摘要相關的代碼。但是,如果我添加總結相關的代碼,我得到了以下錯誤:

InvalidArgumentError (see above for traceback): tags and values not the same shape: [] != [1,1] (tag 'y') 
    [[Node: y = ScalarSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](y/tags, add)]] 

我試圖在正常Python和IPython中。

回答

0

標籤和值的形狀不一樣。你傳遞的是x_var這是一個向量,而summary需要一個標量值。你可以簡單地使用tf.reduce_mean來解決這個問題:

with graph.as_default(): 
    x = tf.placeholder(tf.float32, [None, 2], name='x') 
    W = tf.ones([2, 1], tf.float32, name='W') 
    b = tf.constant([1.5], dtype=tf.float32, shape=(1, 1), name='bias') 
    y_ = tf.add(tf.matmul(x, W, name='mul'), b, name='add') 
    tf.summary.scalar('y', tf.reduce_mean(y_)) 

這將創建一個標量值。

+0

在你的答案和[this](http://www.cloudypoint.com/Tutorials/discussion/python-solved-tensorflow-how-to-tensorboard/)文章的幫助下,我終於得到了代碼工作。我也更新了你的答案。 – davidshen84

+0

**鍵**,輸入** x **不應該是固定大小;在輸出** y **上使用* reduce _ **。 – davidshen84