【问题标题】:TF: Fetch argument x has invalid type <type 'numpy.float32'>, must be a string or Tensor. (Can not convert a float32 into a Tensor or Operation.)TF:Fetch 参数 x 的类型无效 <type 'numpy.float32'>,必须是字符串或张量。 (不能将 float32 转换为张量或操作。)
【发布时间】:2018-01-23 03:43:16
【问题描述】:

我在 TF 中有一个时间序列模型。它基本上是一个简单的自回归模型。

原来的y是一个长度为100的向量(n)。

我得到浮点数不是张量错误(根据主题)。不过,我只在第二种情况下得到它。

LR = .01
STEPS = 100

def Net(x, w, b):
  # x has 2 previous values
  x = [x[-1], x[-2], x[-1] - x[-2]]
  x = tf.reshape(x, [1, 3])
  x = tf.add(tf.matmul(x, w[0]), b[0])
  pred = tf.add(tf.matmul(x, w[1]), b[1])
  return pred

y_data = y - np.mean(y)

x = tf.placeholder(tf.float32, [2], name='x')
y = tf.placeholder(tf.float32, [1], name='y')
w = [tf.Variable(tf.random_normal([3, 3])), tf.Variable(tf.random_normal([3, 1]))]
b = [tf.Variable(tf.random_normal([1])), tf.Variable(tf.random_normal([1]))]
pred = Net(x, w, b)
cost = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(pred, y))))
optimizer = tf.train.AdamOptimizer(learning_rate=LR).minimize(cost)

init = tf.global_variables_initializer()
with tf.Session() as sess:
  sess.run(init)
  for step in range(STEPS):
    # random samples of data
    ts = np.random.choice(np.arange(2, n), int(n * .5), replace=False)
    for t in ts:
      x_data = [y_data[t - 2], y_data[t - 1]]
      y_data_cur = [y_data[t]]
      print(x_data, y_data_cur, x, y, pred)
      _, cost, p = sess.run([optimizer, cost, pred], feed_dict={x: x_data, y: y_data_cur})
      print(cost, p)
    if step % 10 == 0:
      print(step, cost)

【问题讨论】:

  • 我在y_data = y - np.mean(y)这行有错误,这个错误很好理解。
  • 这不是完整的代码,生成y作为形状[100]拳头的随机法线。

标签: python numpy tensorflow


【解决方案1】:

当你运行你的模型时:

_, cost, p = sess.run([optimizer, cost, pred], feed_dict={x: x_data, y: y_data_cur})

您正在用其评估值覆盖 cost 变量,该变量用于保存成本的 TensorFlow 张量,因此下一次迭代失败。只需更改变量的名称:

_, cost_val, p = sess.run([optimizer, cost, pred], feed_dict={x: x_data, y: y_data_cur})

当然,在print 语句中将cost 替换为cost_val

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    相关资源
    最近更新 更多