【问题标题】:How to convert tensorflow variable to numpy array如何将张量流变量转换为numpy数组
【发布时间】:2018-06-27 18:04:18
【问题描述】:

我正在尝试创建一个模型图,其中我的输入是从我的 java 程序输入的 tensorflow 变量 在我的代码中,我使用 numpy 方法,我需要将我的 tensorflow 变量输入转换为 numpy 数组输入

这是我的代码 sn-p

import tensorflow as tf
import numpy as np
eps = np.finfo(float).eps
EXPORT_DIR = './model'

def standardize(x):
   med0 = np.median(x)
   mad0 = np.median(np.abs(x - med0))
   x1 = (x - med0) / (mad0 + eps)
   return x1

#tensorflow input variable
a = tf.placeholder(tf.float32, name="input")
with tf.Session() as session:
session.run(tf.global_variables_initializer())
 #Converting the input variable to numpy array
 tensor = a.eval()

 #calling standardize method
 numpyArray = standardize(tensor)

 #converting numpy array to tf
 tf.convert_to_tensor(numpyArray)

 #creating graph
 graph = tf.get_default_graph()
 tf.train.write_graph(graph, EXPORT_DIR, 'model_graph.pb', as_text=False)

我收到错误:InvalidArgumentError(有关回溯,请参见上文):您必须在行 tensor = a.eval()

当我用常量值代替占位符时,它就会工作并生成图表。但我想从我的 java 代码中输入。 有没有办法做到这一点,或者我需要将我所有的 numpy 方法转换为 tensorflow 方法

【问题讨论】:

  • 您只是转换为 numpy 并返回标准化吗?我宁愿直接在 TF 中这样做。然而,上面可能缺少的是 feed_dict。试试 a.eval(feed_dict={a: })
  • 实际上,我现在没有任何值可以提供,因为我正在使用它作为我的 android 应用程序的模型。更多信息请参考link

标签: python numpy tensorflow


【解决方案1】:

placeholder 只是 tensorflow 中的一个空变量,您可以向其提供 numpy 值。现在,您尝试做的事情没有意义。您无法从空变量中获取值。

如果你想standardize 你的张量,为什么要先把它转换成 numpy var?您可以使用tensorflow 直接执行此操作。

以下取自this stackoverflow ans

def get_median(v):
    v = tf.reshape(v, [-1])
    m = v.get_shape()[0]//2
    return tf.nn.top_k(v, m).values[m-1]

现在,您可以将函数实现为

def standardize(x):
    med0 = get_median(x)
    mad0 = get_median(tf.abs(x - med0))
    x1 = (x - med0)/(mad0 + eps)
    return x1

【讨论】:

  • 它不仅是标准化方法,还有其他各种使用 numpy 的方法。我已经尝试过上述方法,但输出值存在差异。感谢您的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 2018-11-28
相关资源
最近更新 更多