简体   繁体   English

如何将tensorflow变量转换为numpy数组

[英]How to convert tensorflow variable to numpy array

I am trying to create a model graph where my input is tensorflow variable which I am inputting from my java program In my code, I am using numpy methods where I need to convert my tensorflow variable input to numpy array input 我正在尝试创建一个模型图,其中我的输入是我从Java程序输入的tensorflow变量在我的代码中,我使用了numpy方法,需要将我的tensorflow变量输入转换为numpy数组输入

Here, is my code snippet 这是我的代码段

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)

I am getting error : InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input' with dtype float in line tensor = a.eval() 我收到错误消息 :InvalidArgumentError(请参见上面的回溯):您必须在tensor = a.eval()行中使用dtype float来输入占位符张量“ input”的值

When I am giving constant value in place of placeholder then it's working and generating the graph. 当我给定值代替占位符时,它正在工作并生成图形。 But I want to input from my java code. 但是我想从我的Java代码中输入。 Is there any way to do that or do I need to convert all my numpy methods to tensorflow methods 有什么办法做到这一点,还是我需要将所有的numpy方法转换为tensorflow方法?

placeholder is just an empty variable in tensorflow, to which you can feed numpy values. placeholder只是张量流中的一个空变量,您可以向其输入numpy值。 Now, what you are trying to do does not make sense. 现在,您尝试执行的操作没有任何意义。 You can not get value out of an empty variable. 您不能从空变量中获取价值。

If you want to standardize your tensor, why convert it to numpy var first? 如果要standardize张量,为什么要先将其转换为numpy var? You can directly do this using tensorflow . 您可以使用tensorflow直接执行此操作。

The following taken from this stackoverflow ans 以下摘自此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]

Now, you can implement your function as 现在,您可以将功能实现为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM