【问题标题】:How do I convert Tensorflow variables to Matlab structures?如何将 TensorFlow 变量转换为 Matlab 结构?
【发布时间】:2016-08-03 19:00:35
【问题描述】:

我正在尝试将模型参数 (W & b) 从 tensorflow 作为字典传递到 matlab。但是当我将它转换为 matlab 中的结构时,字段仍然是张量变量,我无法对它们进行所需的操作。有没有办法解决这个问题并将它们转换为双精度或矩阵?

在张量流中:

return {'W': W, 'b': b}

在matlab中:

P = py.myModelOutput(samples,labels)
model.parameters = struct(P)

然后,当我在 matlab 中打印结构时,它会显示以下内容:

ans = 

W: [1x1 py.tensorflow.python.ops.variables.Variable]
b: [1x1 py.tensorflow.python.ops.variables.Variable]

尝试将字段转换为双精度也无济于事:

double(model.parameters.W)

使用双精度错误 无法从 py.tensorflow.python.ops.variables.Variable 转换为 double。

【问题讨论】:

  • 您必须先使用session.run将其转换为numpy数组

标签: python matlab data-structures tensorflow type-conversion


【解决方案1】:

假设您的 TensorFlow 程序中有一个名为 sesstf.Session 对象,您应该修改代码以返回以下内容:

def myModelOutput(...):
   # ...
   sess = tf.Session()
   # ...

   # Convert the `tf.Variable` objects `W` and `b` to NumPy arrays.
   W_val, b_val = sess.run([W, b])

   sess.close()  # Assumes `sess` is local to the function.

   return {'W': W_val, 'b': b_val}

【讨论】:

  • 谢谢mcuh!我假设 W.eval() 做同样的工作,还是必须 run()?我最终返回了 W.eval() 和 b.eval() 这将它变成了一个元组而不是字典,但我宁愿返回一个字典。我现在要试试这个。
  • 它是等效的,但是将多个参数传递给sess.run() 可能会更有效,因为这只会调用一次TensorFlow运行时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2014-06-27
  • 2010-10-22
  • 1970-01-01
  • 2021-11-19
相关资源
最近更新 更多