当前位置: 代码迷 >> 综合 >> TensorFlow 使用 tf.summary.FileWriter 添加对标量的统计与观察时报错
  详细解决方案

TensorFlow 使用 tf.summary.FileWriter 添加对标量的统计与观察时报错

热度:16   发布时间:2024-01-14 07:02:35.0

报错信息:

InvalidArgumentError (see above for traceback): tags and values not the same shape: [] != [1,1] (tag 'y')
         [[node y (defined at <stdin>:1)  = ScalarSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](y/tags, add/_5)]]

 

报错源码

(1) 二维数据

>>> import tensorflow as tf
>>> import math
>>> import numpy as np
>>> x = np.linspace(-math.pi,math.pi,300)[:,np.newaxis]
>>> x.shape
# (300, 1)
>>> noise = np.random.normal(loc=0.0, scale=0.9, size=x.shape)
>>> noise.shape
# (300, 1)
>>> x_holder = tf.placeholder(dtype=tf.float32, shape=[None,1], name="x")
>>> x_holder
# <tf.Tensor 'x:0' shape=(?, 1) dtype=float32>
>>> noise_holder = tf.placeholder(dtype=tf.float32, shape=[None,1], name="x")
>>> noise_holder
# <tf.Tensor 'x_1:0' shape=(?, 1) dtype=float32>
>>> y = tf.math.sin(x=x_holder) + noise_holder
>>> 
# <tf.Tensor 'add:0' shape=(?, 1) dtype=float32>>>> summary_writer = tf.summary.FileWriter("./summaries/logdir/")
>>> tf.summary.scalar(name="scalar_y", tensor=y)
>>> merged_summary = tf.summary.merge_all()
>>> init_op = tf.global_variables_initializer()
>>> sess = tf.InteractiveSession()
>>> sess.run(init_op)
>>> for i in range(300):each_x = np.asarray(a=[x[i]], dtype=np.float32)each_noise = np.asarray(a=[noise[i]], dtype=np.float32)summary_result = sess.run(fetches=merged_summary, feed_dict={x_holder:each_x, noise_holder:each_noise})summary_writer.add_summary(summary=summary_result, global_step=i)

(2)一维数据

>>> import tensorflow as tf
>>> import math
>>> import numpy as np>>> x = np.linspace(-math.pi,math.pi,1000)
>>> x.shape
# (1000,)
>>> noise = np.random.normal(loc=0.0, scale=0.9, size=x.shape)
>>> noise.shape
# (1000,)>>> x_holder = tf.placeholder(dtype=tf.float32, shape=[None], name="x")
>>> x_holder
# <tf.Tensor 'x:0' shape=(?,) dtype=float32>
>>> noise_holder = tf.placeholder(dtype=tf.float32, shape=[None], name="x")
>>> noise_holder
# <tf.Tensor 'x_1:0' shape=(?,) dtype=float32>>>> y = tf.math.sin(x=x_holder) + noise_holder
>>> y
# <tf.Tensor 'add:0' shape=(?,) dtype=float32>>>> summary_writer = tf.summary.FileWriter("./summaries/logdir_1d_sin/")
>>> tf.summary.scalar(name="scalar_y", tensor=y)
# <tf.Tensor 'scalar_y:0' shape=() dtype=string>>>> merged_summary = tf.summary.merge_all()>>> init_op = tf.global_variables_initializer()>>> sess = tf.InteractiveSession()
>>> sess.run(init_op)>>> for i in range(1000):each_x = np.asarray(a=[x[i]], dtype=np.float32)each_noise = np.asarray(a=[noise[i]], dtype=np.float32)summary_result = sess.run(fetches=merged_summary, feed_dict={x_holder:each_x, noise_holder:each_noise})summary_writer.add_summary(summary=summary_result, global_step=i)
>>> sess.close()

 

解决方法:将输出结果 y 转换为标量,即在  y = tf.math.sin(x=x_holder) + noise_holder 之后添加

y = tf.reduce_mean(input_tensor=y)

 

  相关解决方案