标签归档:tensorflow

tf.app.run()如何工作?

问题:tf.app.run()如何工作?

tf.app.run()Tensorflow 中的工作如何翻译演示?

在中tensorflow/models/rnn/translate/translate.py,有一个呼叫到tf.app.run()。如何处理?

if __name__ == "__main__":
    tf.app.run() 

How does tf.app.run() work in Tensorflow translate demo?

In tensorflow/models/rnn/translate/translate.py, there is a call to tf.app.run(). How is it being handled?

if __name__ == "__main__":
    tf.app.run() 

回答 0

if __name__ == "__main__":

表示当前文件在shell下执行,而不是作为模块导入。

tf.app.run()

如您所见,通过文件 app.py

def run(main=None, argv=None):
  """Runs the program with an optional 'main' function and 'argv' list."""
  f = flags.FLAGS

  # Extract the args from the optional `argv` list.
  args = argv[1:] if argv else None

  # Parse the known flags from that list, or from the command
  # line otherwise.
  # pylint: disable=protected-access
  flags_passthrough = f._parse_flags(args=args)
  # pylint: enable=protected-access

  main = main or sys.modules['__main__'].main

  # Call the main function, passing through any arguments
  # to the final program.
  sys.exit(main(sys.argv[:1] + flags_passthrough))

让我们逐行中断:

flags_passthrough = f._parse_flags(args=args)

这样可以确保您通过命令行传递的参数有效,例如, python my_model.py --data_dir='...' --max_iteration=10000实际上,此功能是基于python标准argparse模块实现的。

main = main or sys.modules['__main__'].main

第一个main在右边=是当前函数的第一个参数run(main=None, argv=None) 。While sys.modules['__main__']表示当前正在运行的文件(例如my_model.py)。

因此有两种情况:

  1. 您没有的main功能,my_model.py那么您必须调用tf.app.run(my_main_running_function)

  2. 您在中具有main功能my_model.py。(通常是这种情况。)

最后一行:

sys.exit(main(sys.argv[:1] + flags_passthrough))

确保使用解析后的参数正确调用您的main(argv)or my_main_running_function(argv)函数。

if __name__ == "__main__":

means current file is executed under a shell instead of imported as a module.

tf.app.run()

As you can see through the file app.py

def run(main=None, argv=None):
  """Runs the program with an optional 'main' function and 'argv' list."""
  f = flags.FLAGS

  # Extract the args from the optional `argv` list.
  args = argv[1:] if argv else None

  # Parse the known flags from that list, or from the command
  # line otherwise.
  # pylint: disable=protected-access
  flags_passthrough = f._parse_flags(args=args)
  # pylint: enable=protected-access

  main = main or sys.modules['__main__'].main

  # Call the main function, passing through any arguments
  # to the final program.
  sys.exit(main(sys.argv[:1] + flags_passthrough))

Let’s break line by line:

flags_passthrough = f._parse_flags(args=args)

This ensures that the argument you pass through command line is valid,e.g. python my_model.py --data_dir='...' --max_iteration=10000 Actually, this feature is implemented based on python standard argparse module.

main = main or sys.modules['__main__'].main

The first main in right side of = is the first argument of current function run(main=None, argv=None) . While sys.modules['__main__'] means current running file(e.g. my_model.py).

So there are two cases:

  1. You don’t have a main function in my_model.py Then you have to call tf.app.run(my_main_running_function)

  2. you have a main function in my_model.py. (This is mostly the case.)

Last line:

sys.exit(main(sys.argv[:1] + flags_passthrough))

ensures your main(argv) or my_main_running_function(argv) function is called with parsed arguments properly.


回答 1

这只是一个非常快速的包装程序,可以处理标志解析,然后分派到您自己的主程序。参见代码

It’s just a very quick wrapper that handles flag parsing and then dispatches to your own main. See the code.


回答 2

没什么特别的tf.app。这只是一个通用的入口点脚本

使用可选的“ main”功能和“ argv”列表运行程序。

它与神经网络无关,它只是调用main函数,并传递给它的任何参数。

There is nothing special in tf.app. This is just a generic entry point script, which

Runs the program with an optional ‘main’ function and ‘argv’ list.

It has nothing to do with neural networks and it just calls the main function, passing through any arguments to it.


回答 3

简单来说,的工作tf.app.run()首先设置全局标志以供以后使用,例如:

from tensorflow.python.platform import flags
f = flags.FLAGS

然后使用一组参数运行自定义的main函数。

例如,在TensorFlow NMT代码库中,用于训练/推理的程序执行的第一个入口点就是从这一点开始(请参见下面的代码)

if __name__ == "__main__":
  nmt_parser = argparse.ArgumentParser()
  add_arguments(nmt_parser)
  FLAGS, unparsed = nmt_parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

在使用解析参数之后argparsetf.app.run()您将运行函数“ main”,其定义如下:

def main(unused_argv):
  default_hparams = create_hparams(FLAGS)
  train_fn = train.train
  inference_fn = inference.inference
  run_main(FLAGS, default_hparams, train_fn, inference_fn)

因此,在设置了供全局使用的标志之后,tf.app.run()只需运行main传递给它的函数argv作为其参数即可。

PS:正如萨尔瓦多·达利(Salvador Dali)的回答所说,我猜这只是一个很好的软件工程实践,尽管我不确定TensorFlow是否会执行main比使用常规CPython 进行的函数优化的运行。

In simple terms, the job of tf.app.run() is to first set the global flags for later usage like:

from tensorflow.python.platform import flags
f = flags.FLAGS

and then run your custom main function with a set of arguments.

For e.g. in TensorFlow NMT codebase, the very first entry point for the program execution for training/inference starts at this point (see below code)

if __name__ == "__main__":
  nmt_parser = argparse.ArgumentParser()
  add_arguments(nmt_parser)
  FLAGS, unparsed = nmt_parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

After parsing the arguments using argparse, with tf.app.run() you run the function “main” which is defined like:

def main(unused_argv):
  default_hparams = create_hparams(FLAGS)
  train_fn = train.train
  inference_fn = inference.inference
  run_main(FLAGS, default_hparams, train_fn, inference_fn)

So, after setting the flags for global use, tf.app.run() simply runs that main function that you pass to it with argv as its parameters.

P.S.: As Salvador Dali’s answer says, it’s just a good software engineering practice, I guess, although I’m not sure whether TensorFlow performs any optimized run of the main function than that was run using normal CPython.


回答 4

Google代码很大程度上取决于要在库/二进制文件/ python脚本中访问的全局标志,因此tf.app.run()解析出这些标志以在FLAGs(或类似的变量)中创建全局状态,然后调用python main( ) 正如它应该。

如果他们没有对tf.app.run()的调用,则用户可能会忘记进行FLAG解析,从而导致这些库/二进制文件/脚本无法访问所需的FLAG。

Google code depends on a lot on global flags being accessing in libraries/binaries/python scripts and so tf.app.run() parses out those flags to create a global state in FLAGs(or something similar) variable and then calls python main() as it should.

If they didn’t have this call to tf.app.run(), then users might forget to do FLAGs parsing, leading to these libraries/binaries/scripts not having access to FLAGs they need.


回答 5

2.0兼容答:如果你想使用tf.app.run()Tensorflow 2.0,我们应该使用的命令,

tf.compat.v1.app.run()或者您可以使用tf_upgrade_v21.x代码转换为2.0

2.0 Compatible Answer: If you want to use tf.app.run() in Tensorflow 2.0, we should use the command,

tf.compat.v1.app.run() or you can use tf_upgrade_v2 to convert 1.x code to 2.0.


TensorFlow,为什么选择python语言?

问题:TensorFlow,为什么选择python语言?

我最近开始研究深度学习和其他ML技术,并开始寻找简化构建网络并对其进行培训的框架,然后我发现TensorFlow在该领域经验不足,对我来说,速度似乎是如果与深度学习一起工作,那么使大型机器学习系统变得更大的重要因素,那么为什么Google选择python来制造TensorFlow?用一种可以编译且无法解释的语言来编写代码会更好吗?

使用Python而不是像C ++这样的语言进行机器学习有什么优势?

I recently started studying deep learning and other ML techniques, and I started searching for frameworks that simplify the process of build a net and training it, then I found TensorFlow, having little experience in the field, for me, it seems that speed is a big factor for making a big ML system even more if working with deep learning, so why python was chosen by Google to make TensorFlow? Wouldn’t it be better to make it over an language that can be compiled and not interpreted?

What are the advantages of using Python over a language like C++ for machine learning?


回答 0

关于TensorFlow的最重要的认识是,在大多数情况下,内核不是用Python编写的:它是由高度优化的C ++和CUDA(Nvidia用于GPU编程的语言)结合而成。反过来,大多数情况是通过使用Eigen(高性能C ++和CUDA数值库)和NVidia的cuDNN(为NVidia GPU进行了非常优化的DNN库,用于诸如卷积之类的功能)而发生的。

TensorFlow的模型是程序员使用“某种语言”(很可能是Python!)来表达模型。该模型以TensorFlow构造编写,例如:

h1 = tf.nn.relu(tf.matmul(l1, W1) + b1)
h2 = ...

在运行Python时实际上并未执行。相反,实际创建的是一个数据流图,该表示接受特定的输入,应用特定的操作,将结果作为输入提供给其他操作,等等。 该模型由快速的C ++代码执行,并且在大多数情况下,操作之间传递的数据永远不会复制回Python代码

然后,程序员通过拉上节点来“驱动”该模型的执行-通常在Python中进行训练,有时在Python中甚至在原始C ++中进行服务:

sess.run(eval_results)

这个Python(或C ++函数调用)使用对C ++的进程内调用或针对分布式版本的RPC来调用C ++ TensorFlow服务器以使其执行,然后将结果复制回去。

因此,话虽如此,让我们重新表述一下问题:为什么TensorFlow为什么选择Python作为表达和控制模型训练的第一种得到良好支持的语言?

答案很简单:对于许多数据科学家和机器学习专家来说,Python可能最舒适的语言,它易于集成并可以控制C ++后端,同时在内部和外部也广泛使用。和开放源代码。鉴于使用TensorFlow的基本模型,Python的性能并不那么重要,因此很自然。NumPy的巨大优势还在于它可以在Python中轻松进行预处理-同时具有高性能-在将其输入TensorFlow进行真正占用大量CPU的处理之前。

表示执行模型时不使用的模型也有很多复杂性-形状推断(例如,如果您做matmul(A,B),结果数据的形状是什么?)和自动梯度计算。事实证明,能够用Python表达这些内容真是太好了,尽管从长远来看,我认为它们可能会转移到C ++后端以使添加其他语言变得更加容易。

(当然,希望是将来支持其他语言来创建和表达模型。使用其他几种语言来运行推理已经非常简单了-C ++现在可以工作了,Facebook的某人贡献了Go绑定,我们现在正在对其进行审查。等)

The most important thing to realize about TensorFlow is that, for the most part, the core is not written in Python: It’s written in a combination of highly-optimized C++ and CUDA (Nvidia’s language for programming GPUs). Much of that happens, in turn, by using Eigen (a high-performance C++ and CUDA numerical library) and NVidia’s cuDNN (a very optimized DNN library for NVidia GPUs, for functions such as convolutions).

The model for TensorFlow is that the programmer uses “some language” (most likely Python!) to express the model. This model, written in the TensorFlow constructs such as:

h1 = tf.nn.relu(tf.matmul(l1, W1) + b1)
h2 = ...

is not actually executed when the Python is run. Instead, what’s actually created is a dataflow graph that says to take particular inputs, apply particular operations, supply the results as the inputs to other operations, and so on. This model is executed by fast C++ code, and for the most part, the data going between operations is never copied back to the Python code.

Then the programmer “drives” the execution of this model by pulling on nodes — for training, usually in Python, and for serving, sometimes in Python and sometimes in raw C++:

sess.run(eval_results)

This one Python (or C++ function call) uses either an in-process call to C++ or an RPC for the distributed version to call into the C++ TensorFlow server to tell it to execute, and then copies back the results.

So, with that said, let’s re-phrase the question: Why did TensorFlow choose Python as the first well-supported language for expressing and controlling the training of models?

The answer to that is simple: Python is probably the most comfortable language for a large range of data scientists and machine learning experts that’s also that easy to integrate and have control a C++ backend, while also being general, widely-used both inside and outside of Google, and open source. Given that with the basic model of TensorFlow, the performance of Python isn’t that important, it was a natural fit. It’s also a huge plus that NumPy makes it easy to do pre-processing in Python — also with high performance — before feeding it in to TensorFlow for the truly CPU-heavy things.

There’s also a bunch of complexity in expressing the model that isn’t used when executing it — shape inference (e.g., if you do matmul(A, B), what is the shape of the resulting data?) and automatic gradient computation. It turns out to have been nice to be able to express those in Python, though I think in the long term they’ll probably move to the C++ backend to make adding other languages easier.

(The hope, of course, is to support other languages in the future for creating and expressing models. It’s already quite straightforward to run inference using several other languages — C++ works now, someone from Facebook contributed Go bindings that we’re reviewing now, etc.)


回答 1

TF不是用python编写的。它是用C ++编写的(并使用高性能的数字CUDA代码),您可以通过查看他们的github进行检查。因此,核心不是用python编写的,而是TF提供了许多其他语言(python,C ++,Java,Go)的接口

在此处输入图片说明

如果您来自数据分析领域,则可以像numpy(不是用python编写,但提供了Python的接口)那样考虑它,或者如果您是Web开发人员,则可以将其视为数据库(PostgreSQL,MySQL,可以从Java,Python,PHP调用)


由于许多 原因, Python前端(人们使用TF编写模型的语言)最受欢迎。在我看来,主要原因是历史原因:大多数ML用户已经在使用它(另一个流行的选择是R),因此,如果您不提供python的接口,那么您的库很可能注定会变得晦涩难懂。


但是用python编写并不意味着您的模型是用python执行的。相反,如果您以正确的方式编写模型,则在评估TF图期间绝不会执行Python(tf.py_func()除外,该存在于调试中,应在实际模型中避免使用,因为它是在Python方面)。

例如,这与numpy不同。例如,如果您这样做np.linalg.eig(np.matmul(A, np.transpose(A))(是eig(AA')),则该操作将以某种快速语言(C ++或fortran)计算转置,将其返回给python,将其与python一起从python中取出,并以某种快速语言计算一个乘法并将其返回给python,然后计算特征值并将其返回给python。因此,尽管有效地计算了诸如matmul和eig之类的昂贵操作,但您仍然需要通过将结果移回python并强制执行来浪费时间。TF不会这样做,一旦定义了图,张量就不会在python中,而是在C ++ / CUDA /其他地方流动。

TF is not written in python. It is written in C++ (and uses high-performant numerical libraries and CUDA code) and you can check this by looking at their github. So the core is written not in python but TF provide an interface to many other languages (python, C++, Java, Go)

enter image description here

If you come from a data analysis world, you can think about it like numpy (not written in python, but provides an interface to Python) or if you are a web-developer – think about it as a database (PostgreSQL, MySQL, which can be invoked from Java, Python, PHP)


Python frontend (the language in which people write models in TF) is the most popular due to many reasons. In my opinion the main reason is historical: majority of ML users already use it (another popular choice is R) so if you will not provide an interface to python, your library is most probably doomed to obscurity.


But being written in python does not mean that your model is executed in python. On the contrary, if you written your model in the right way Python is never executed during the evaluation of the TF graph (except of tf.py_func(), which exists for debugging and should be avoided in real model exactly because it is executed on Python’s side).

This is different from for example numpy. For example if you do np.linalg.eig(np.matmul(A, np.transpose(A)) (which is eig(AA')), the operation will compute transpose in some fast language (C++ or fortran), return it to python, take it from python together with A, and compute a multiplication in some fast language and return it to python, then compute eigenvalues and return it to python. So nonetheless expensive operations like matmul and eig are calculated efficiently, you still lose time by moving the results to python back and force. TF does not do it, once you defined the graph your tensors flow not in python but in C++/CUDA/something else.


回答 2

Python允许您使用C和C ++创建扩展模块,与本机代码接口,并且仍然获得Python给您的优势。

TensorFlow使用Python,是的,但是它也包含大量的C ++

这样就可以使用更简单的界面进行实验,从而减少了用Python进行的人工操作,并通过对C ++中最重要的部分进行编程来提高性能。

Python allows you to create extension modules using C and C++, interfacing with native code, and still getting the advantages that Python gives you.

TensorFlow uses Python, yes, but it also contains large amounts of C++.

This allows a simpler interface for experimentation with less human-thought overhead with Python, and add performance by programming the most important parts in C++.


回答 3

您可以从此处查看的最新比率显示TensorFlow C ++内部需要约50%的代码,而Python需要约40%的代码。

C ++和Python都是Google的官方语言,所以也难怪为什么会这样。如果我必须在存在C ++和Python的地方提供快速回归…

C ++在计算代数内部,Python用于其他所有方面,包括测试。知道今天的测试无处不在,难怪Python代码对TF做出了如此大的贡献。

The latest ratio you can check from here shows inside TensorFlow C++ takes ~50% of code, and Python takes ~40% of code.

Both C++ and Python are the official languages at Google so there is no wonder why this is so. If I would have to provide fast regression where C++ and Python are present…

C++ is inside the computational algebra, and Python is used for everything else including for the testing. Knowing how ubiquitous the testing is today it is no wonder why Python code contributes that much to TF.


在TensorFlow中,Session.run()和Tensor.eval()有什么区别?

问题:在TensorFlow中,Session.run()和Tensor.eval()有什么区别?

TensorFlow有两种评估图形部分的方法:Session.run在变量列表和上Tensor.eval。两者之间有区别吗?

TensorFlow has two ways to evaluate part of graph: Session.run on a list of variables and Tensor.eval. Is there a difference between these two?


回答 0

如果您有Tensort,则调用t.eval()等效于tf.get_default_session().run(t)

您可以将会话设置为默认会话,如下所示:

t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.get_default_session()
    assert t.eval() == sess.run(t)

最重要的区别是,您可以sess.run()在同一步骤中用来获取许多张量的值:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

请注意,每次调用evalrun都会从头开始执行整个图形。要缓存计算结果,请将其分配给tf.Variable

If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).

You can make a session the default as follows:

t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.get_default_session()
    assert t.eval() == sess.run(t)

The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Note that each call to eval and run will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable.


回答 1

关于张量流的FAQ会话对完全相同的问题有一个答案。我将继续并将其留在这里:


如果tTensor对象,t.eval()则为的简写形式sess.run(t)sess当前的默认会话在哪里。以下两个代码段是等效的:

sess = tf.Session()
c = tf.constant(5.0)
print sess.run(c)

c = tf.constant(5.0)
with tf.Session():
  print c.eval()

在第二个示例中,会话充当上下文管理器,其作用是将其安装为with块生存期内的默认会话。上下文管理器方法可以为简单的用例(例如单元测试)生成更简洁的代码;如果您的代码涉及多个图形和会话,则显式调用可能更直接Session.run()

我建议您至少在整个FAQ中略读一遍,因为它可能会阐明很多事情。

The FAQ session on tensor flow has an answer to exactly the same question. I will just go ahead and leave it here:


If t is a Tensor object, t.eval() is shorthand for sess.run(t) (where sess is the current default session. The two following snippets of code are equivalent:

sess = tf.Session()
c = tf.constant(5.0)
print sess.run(c)

c = tf.constant(5.0)
with tf.Session():
  print c.eval()

In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the with block. The context manager approach can lead to more concise code for simple use cases (like unit tests); if your code deals with multiple graphs and sessions, it may be more straightforward to explicit calls to Session.run().

I’d recommend that you at least skim throughout the whole FAQ, as it might clarify a lot of things.


回答 2

eval() 无法处理列表对象

tf.reset_default_graph()

a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
    z = a * tf.cos(z + i) + z * tf.sin(b - i)
grad = tf.gradients(z, [a, b])

init = tf.global_variables_initializer()

with tf.Session() as sess:
    init.run()
    print("z:", z.eval())
    print("grad", grad.eval())

但是Session.run()可以

print("grad", sess.run(grad))

如果我错了请纠正我

eval() can not handle the list object

tf.reset_default_graph()

a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
    z = a * tf.cos(z + i) + z * tf.sin(b - i)
grad = tf.gradients(z, [a, b])

init = tf.global_variables_initializer()

with tf.Session() as sess:
    init.run()
    print("z:", z.eval())
    print("grad", grad.eval())

but Session.run() can

print("grad", sess.run(grad))

correct me if I am wrong


回答 3

要记住的最重要的事情:

从TenorFlow获取常量,变量(任何结果)的唯一方法是会话。

知道这一切很容易

两者tf.Session.run()tf.Tensor.eval()从会话中获取结果,这tf.Tensor.eval()是调用的快捷方式tf.get_default_session().run(t)


我还将tf.Operation.run()这里概述该方法:

在会话中启动图形后,可以通过将操作传递到来执行操作tf.Session.run()op.run()是呼叫的捷径tf.get_default_session().run(op)

The most important thing to remember:

The only way to get a constant, variable (any result) from TenorFlow is the session.

Knowing this everything else is easy:

Both tf.Session.run() and tf.Tensor.eval() get results from the session where tf.Tensor.eval() is a shortcut for calling tf.get_default_session().run(t)


I would also outline the method tf.Operation.run() as in here:

After the graph has been launched in a session, an Operation can be executed by passing it to tf.Session.run(). op.run() is a shortcut for calling tf.get_default_session().run(op).


回答 4

在tensorflow中,您可以创建图并将值传递给该图。Graph会做所有的工作,并根据您在图中进行的配置来生成输出。现在,当您将值传递给图形时,首先需要创建一个tensorflow会话。

tf.Session()

会话初始化后,您应该使用该会话,因为所有变量和设置现在都属于该会话。因此,有两种方法可以将外部值传递给图,以便图接受它们。一种是在使用正在执行的会话时调用.run()。

基本上是该方法的捷径的其他方法是使用.eval()。我说捷径是因为.eval()的完整形式是

tf.get_default_session().run(values)

您可以自己检查。在values.eval()奔跑的地方tf.get_default_session().run(values)。您必须得到相同的行为。

eval的操作是使用默认会话,然后执行run()。

In tensorflow you create graphs and pass values to that graph. Graph does all the hardwork and generate the output based on the configuration that you have made in the graph. Now When you pass values to the graph then first you need to create a tensorflow session.

tf.Session()

Once session is initialized then you are supposed to use that session because all the variables and settings are now part of the session. So, there are two ways to pass external values to the graph so that graph accepts them. One is to call the .run() while you are using the session being executed.

Other way which is basically a shortcut to this is to use .eval(). I said shortcut because the full form of .eval() is

tf.get_default_session().run(values)

You can check that yourself. At the place of values.eval() run tf.get_default_session().run(values). You must get the same behavior.

what eval is doing is using the default session and then executing run().


回答 5

Tensorflow 2.x兼容答案:将mrry的代码转换Tensorflow 2.x (>= 2.0)为社区的利益。

!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()    

t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.compat.v1.get_default_session()
    assert t.eval() == sess.run(t)

#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Tensorflow 2.x Compatible Answer: Converting mrry’s code to Tensorflow 2.x (>= 2.0) for the benefit of the community.

!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()    

t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.compat.v1.get_default_session()
    assert t.eval() == sess.run(t)

#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

禁用Tensorflow调试信息

问题:禁用Tensorflow调试信息

通过调试信息,我的意思是TensorFlow在我的终端中显示的有关加载的库和找到的设备等的内容,不是Python错误。

I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcurand.so locally
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:900] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties: 
name: Graphics Device
major: 5 minor: 2 memoryClockRate (GHz) 1.0885
pciBusID 0000:04:00.0
Total memory: 12.00GiB
Free memory: 11.83GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0 
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:717] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Graphics Device, pci bus id: 0000:04:00.0)
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.0KiB
...

By debugging information I mean what TensorFlow shows in my terminal about loaded libraries and found devices etc. not Python errors.

I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcurand.so locally
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:900] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties: 
name: Graphics Device
major: 5 minor: 2 memoryClockRate (GHz) 1.0885
pciBusID 0000:04:00.0
Total memory: 12.00GiB
Free memory: 11.83GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0 
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:717] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Graphics Device, pci bus id: 0000:04:00.0)
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.0KiB
...

回答 0

您可以使用os.environ以下命令禁用所有调试日志:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 
import tensorflow as tf

在tf 0.12和1.0上测试

详细来说,

0 = all messages are logged (default behavior)
1 = INFO messages are not printed
2 = INFO and WARNING messages are not printed
3 = INFO, WARNING, and ERROR messages are not printed

You can disable all debugging logs using os.environ :

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 
import tensorflow as tf

Tested on tf 0.12 and 1.0

In details,

0 = all messages are logged (default behavior)
1 = INFO messages are not printed
2 = INFO and WARNING messages are not printed
3 = INFO, WARNING, and ERROR messages are not printed

回答 1

2.0更新(10/8/19) 设置TF_CPP_MIN_LOG_LEVEL仍然应该起作用(请参见v0.12 +更新中的以下内容),但是当前存在一个未解决的问题(请参阅问题#31870)。如果该设置TF_CPP_MIN_LOG_LEVEL对您不起作用(再次参见下文),请尝试执行以下操作来设置日志级别:

import tensorflow as tf
tf.get_logger().setLevel('INFO')

此外,请参阅有关tf.autograph.set_verbosity设置签名日志消息详细程度的文档-例如:

# Can also be set using the AUTOGRAPH_VERBOSITY environment variable
tf.autograph.set_verbosity(1)

v0.12 +更新(5/20/17),通过TF 2.0+进行工作:

在TensorFlow 0.12+中,针对此问题,您现在可以通过称为TF_CPP_MIN_LOG_LEVEL; 的环境变量控制日志记录。它默认为0(显示所有日志),但可以设置为该Level列下的以下值之一。

  Level | Level for Humans | Level Description                  
 -------|------------------|------------------------------------ 
  0     | DEBUG            | [Default] Print all messages       
  1     | INFO             | Filter out INFO messages           
  2     | WARNING          | Filter out INFO & WARNING messages 
  3     | ERROR            | Filter out all messages      

请参阅以下使用Python的通用OS示例:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}
import tensorflow as tf

为了更全面,您还调用了设置Python tf_logging模块的级别,该模块用于摘要操作,张量板,各种估计器等。

# append to lines above
tf.logging.set_verbosity(tf.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}

对于1.14,如果不按以下说明使用v1 API,则会收到警告:

# append to lines above
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}


对于TensorFlow或TF-Learn日志的早期版本(v0.11.x或更低版本):

查看以下页面以获取有关TensorFlow日志记录的信息; 与新的更新,你能在日志记录级别设置为DEBUGINFOWARNERROR,或FATAL。例如:

tf.logging.set_verbosity(tf.logging.ERROR)

该页面还翻过了可与TF-Learn模型一起使用的监视器。这是页面

但是,这不会阻止所有日志记录(仅TF-Learn)。我有两种解决方案;一种是“技术上正确”的解决方案(Linux),另一种是重建TensorFlow。

script -c 'python [FILENAME].py' | grep -v 'I tensorflow/'

对于其他,请参见此答案,其中涉及修改源和重建TensorFlow。

2.0 Update (10/8/19) Setting TF_CPP_MIN_LOG_LEVEL should still work (see below in v0.12+ update), but there is currently an issue open (see issue #31870). If setting TF_CPP_MIN_LOG_LEVEL does not work for you (again, see below), try doing the following to set the log level:

import tensorflow as tf
tf.get_logger().setLevel('INFO')

In addition, please see the documentation on tf.autograph.set_verbosity which sets the verbosity of autograph log messages – for example:

# Can also be set using the AUTOGRAPH_VERBOSITY environment variable
tf.autograph.set_verbosity(1)

v0.12+ Update (5/20/17), Working through TF 2.0+:

In TensorFlow 0.12+, per this issue, you can now control logging via the environmental variable called TF_CPP_MIN_LOG_LEVEL; it defaults to 0 (all logs shown) but can be set to one of the following values under the Level column.

  Level | Level for Humans | Level Description                  
 -------|------------------|------------------------------------ 
  0     | DEBUG            | [Default] Print all messages       
  1     | INFO             | Filter out INFO messages           
  2     | WARNING          | Filter out INFO & WARNING messages 
  3     | ERROR            | Filter out all messages      

See the following generic OS example using Python:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}
import tensorflow as tf

To be thorough, you call also set the level for the Python tf_logging module, which is used in e.g. summary ops, tensorboard, various estimators, etc.

# append to lines above
tf.logging.set_verbosity(tf.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}

For 1.14 you will receive warnings if you do not change to use the v1 API as follows:

# append to lines above
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}


For Prior Versions of TensorFlow or TF-Learn Logging (v0.11.x or lower):

View the page below for information on TensorFlow logging; with the new update, you’re able to set the logging verbosity to either DEBUG, INFO, WARN, ERROR, or FATAL. For example:

tf.logging.set_verbosity(tf.logging.ERROR)

The page additionally goes over monitors which can be used with TF-Learn models. Here is the page.

This doesn’t block all logging, though (only TF-Learn). I have two solutions; one is a ‘technically correct’ solution (Linux) and the other involves rebuilding TensorFlow.

script -c 'python [FILENAME].py' | grep -v 'I tensorflow/'

For the other, please see this answer which involves modifying source and rebuilding TensorFlow.


回答 2

我也有这个问题(位于tensorflow-0.10.0rc0),但是无法通过建议的答案解决过多的鼻子测试记录问题。

我设法通过直接研究tensorflow记录器来解决这个问题。不是最正确的修复程序,但效果很好,并且只会污染直接或间接导入张量流的测试文件:

# Place this before directly or indirectly importing tensorflow
import logging
logging.getLogger("tensorflow").setLevel(logging.WARNING)

I have had this problem as well (on tensorflow-0.10.0rc0), but could not fix the excessive nose tests logging problem via the suggested answers.

I managed to solve this by probing directly into the tensorflow logger. Not the most correct of fixes, but works great and only pollutes the test files which directly or indirectly import tensorflow:

# Place this before directly or indirectly importing tensorflow
import logging
logging.getLogger("tensorflow").setLevel(logging.WARNING)

回答 3

为了与Tensorflow 2.0兼容,您可以使用tf.get_logger

import logging
tf.get_logger().setLevel(logging.ERROR)

For compatibility with Tensorflow 2.0, you can use tf.get_logger

import logging
tf.get_logger().setLevel(logging.ERROR)

回答 4

由于TF_CPP_MIN_LOG_LEVEL对我不起作用,您可以尝试:

tf.logging.set_verbosity(tf.logging.WARN)

在Tensorflow v1.6.0中为我工作

As TF_CPP_MIN_LOG_LEVEL didn’t work for me you can try:

tf.logging.set_verbosity(tf.logging.WARN)

Worked for me in tensorflow v1.6.0


回答 5

通常的python3日志管理器为我使用tensorflow == 1.11.0:

import logging
logging.getLogger('tensorflow').setLevel(logging.INFO)

Usual python3 log manager works for me with tensorflow==1.11.0:

import logging
logging.getLogger('tensorflow').setLevel(logging.INFO)

回答 6

我用这篇文章解决了无法删除所有警告#27045,解决方法是:

import logging
logging.getLogger('tensorflow').disabled = True

I solved with this post Cannot remove all warnings #27045 , and the solution was:

import logging
logging.getLogger('tensorflow').disabled = True

回答 7

为了在此处增加一些灵活性,您可以编写一个函数来过滤出您喜欢的消息,从而实现对日志记录级别的更精细控制:

logging.getLogger('tensorflow').addFilter(my_filter_func)

其中,如果您希望抛出该消息,则my_filter_func接受一个LogRecord对象作为输入[ LogRecorddocs ]并返回零;否则为非零。

这是一个示例过滤器,仅保留每第n条信息消息(由于使用了nonlocalhere ,因此使用了Python 3 ):

def keep_every_nth_info(n):
    i = -1
    def filter_record(record):
        nonlocal i
        i += 1
        return int(record.levelname != 'INFO' or i % n == 0)
    return filter_record

# Example usage for TensorFlow:
logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))

以上所有假设均假设TensorFlow已设置其日志记录状态。您可以通过tf.logging.get_verbosity()添加过滤器之前进行调用来确保没有副作用。

To add some flexibility here, you can achieve more fine-grained control over the level of logging by writing a function that filters out messages however you like:

logging.getLogger('tensorflow').addFilter(my_filter_func)

where my_filter_func accepts a LogRecord object as input [LogRecord docs] and returns zero if you want the message thrown out; nonzero otherwise.

Here’s an example filter that only keeps every nth info message (Python 3 due to the use of nonlocal here):

def keep_every_nth_info(n):
    i = -1
    def filter_record(record):
        nonlocal i
        i += 1
        return int(record.levelname != 'INFO' or i % n == 0)
    return filter_record

# Example usage for TensorFlow:
logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))

All of the above has assumed that TensorFlow has set up its logging state already. You can ensure this without side effects by calling tf.logging.get_verbosity() before adding a filter.


回答 8

是的,我正在使用tf 2.0-beta,并且想要启用/禁用默认日志记录。tf1.X中的环境变量和方法似乎不再存在。

我进入PDB,发现它可以正常工作:

# close the TF2 logger
tf2logger = tf.get_logger()
tf2logger.error('Close TF2 logger handlers')
tf2logger.root.removeHandler(tf2logger.root.handlers[0])

然后,我添加自己的记录器API(在这种情况下,基于文件)

logtf = logging.getLogger('DST')
logtf.setLevel(logging.DEBUG)

# file handler
logfile='/tmp/tf_s.log'
fh = logging.FileHandler(logfile)
fh.setFormatter( logging.Formatter('fh %(asctime)s %(name)s %(filename)s:%(lineno)d :%(message)s') )
logtf.addHandler(fh)
logtf.info('writing to %s', logfile)

Yeah, I’m using tf 2.0-beta and want to enable/disable the default logging. The environment variable and methods in tf1.X don’t seem to exist anymore.

I stepped around in PDB and found this to work:

# close the TF2 logger
tf2logger = tf.get_logger()
tf2logger.error('Close TF2 logger handlers')
tf2logger.root.removeHandler(tf2logger.root.handlers[0])

I then add my own logger API (in this case file-based)

logtf = logging.getLogger('DST')
logtf.setLevel(logging.DEBUG)

# file handler
logfile='/tmp/tf_s.log'
fh = logging.FileHandler(logfile)
fh.setFormatter( logging.Formatter('fh %(asctime)s %(name)s %(filename)s:%(lineno)d :%(message)s') )
logtf.addHandler(fh)
logtf.info('writing to %s', logfile)

回答 9

对于tensorflow 2.1.0,以下代码可以正常工作。

import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

for tensorflow 2.1.0, following code works fine.

import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

回答 10

如果您只需要消除屏幕上的警告输出,则可以使用以下简单命令在导入tensorflow之后立即清除控制台屏幕(根据我的经验,它比禁用所有调试日志更有效):

在Windows中:

import os
os.system('cls')

在Linux或Mac中:

import os
os.system('clear')

If you only need to get rid of warning outputs on the screen, you might want to clear the console screen right after importing the tensorflow by using this simple command (Its more effective than disabling all debugging logs in my experience):

In windows:

import os
os.system('cls')

In Linux or Mac:

import os
os.system('clear')

如何在TensorFlow中将张量转换为numpy数组?

问题:如何在TensorFlow中将张量转换为numpy数组?

将Tensorflow与Python绑定一起使用时,如何将张量转换为numpy数组?

How to convert a tensor into a numpy array when using Tensorflow with Python bindings?


回答 0

Session.runeval为NumPy数组返回的任何张量。

>>> print(type(tf.Session().run(tf.constant([1,2,3]))))
<class 'numpy.ndarray'>

要么:

>>> sess = tf.InteractiveSession()
>>> print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

或者,等效地:

>>> sess = tf.Session()
>>> with sess.as_default():
>>>    print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

编辑:不是任何张量返回Session.run或是eval()一个NumPy数组。例如,稀疏张量作为SparseTensorValue返回:

>>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>

Any tensor returned by Session.run or eval is a NumPy array.

>>> print(type(tf.Session().run(tf.constant([1,2,3]))))
<class 'numpy.ndarray'>

Or:

>>> sess = tf.InteractiveSession()
>>> print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

Or, equivalently:

>>> sess = tf.Session()
>>> with sess.as_default():
>>>    print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

EDIT: Not any tensor returned by Session.run or eval() is a NumPy array. Sparse Tensors for example are returned as SparseTensorValue:

>>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>

回答 1

要将张量转换回numpy数组,您只需.eval()在转换后的张量上运行即可。

To convert back from tensor to numpy array you can simply run .eval() on the transformed tensor.


回答 2

TensorFlow 2.x

急切执行默认情况下.numpy()处于启用状态,因此只需调用Tensor对象即可。

import tensorflow as tf

a = tf.constant([[1, 2], [3, 4]])                 
b = tf.add(a, 1)

a.numpy()
# array([[1, 2],
#        [3, 4]], dtype=int32)

b.numpy()
# array([[2, 3],
#        [4, 5]], dtype=int32)

tf.multiply(a, b).numpy()
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

值得注意的是(来自文档),

Numpy数组可以与Tensor对象共享内存。对一个的任何更改都可能反映在另一个上。

大胆强调我的。副本可能会也可能不会返回,这是一个实现细节。


如果禁用了“急切执行”,则可以构建一个图形,然后通过tf.compat.v1.Session以下方式运行它:

a = tf.constant([[1, 2], [3, 4]])                 
b = tf.add(a, 1)
out = tf.multiply(a, b)

out.eval(session=tf.compat.v1.Session())    
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

另请参见TF 2.0符号映射,以获取旧API到新API的映射。

TensorFlow 2.x

Eager Execution is enabled by default, so just call .numpy() on the Tensor object.

import tensorflow as tf

a = tf.constant([[1, 2], [3, 4]])                 
b = tf.add(a, 1)

a.numpy()
# array([[1, 2],
#        [3, 4]], dtype=int32)

b.numpy()
# array([[2, 3],
#        [4, 5]], dtype=int32)

tf.multiply(a, b).numpy()
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

See NumPy Compatibility for more. It is worth noting (from the docs),

Numpy array may share memory with the Tensor object. Any changes to one may be reflected in the other.

Bold emphasis mine. A copy may or may not be returned, and this is an implementation detail based on whether the data is in CPU or GPU (in the latter case, a copy has to be made from GPU to host memory).

But why am I getting AttributeError: 'Tensor' object has no attribute 'numpy'?.
A lot of folks have commented about this issue, there are a couple of possible reasons:

  • TF 2.0 is not correctly installed (in which case, try re-installing), or
  • TF 2.0 is installed, but eager execution is disabled for some reason. In such cases, call tf.compat.v1.enable_eager_execution() to enable it, or see below.

If Eager Execution is disabled, you can build a graph and then run it through tf.compat.v1.Session:

a = tf.constant([[1, 2], [3, 4]])                 
b = tf.add(a, 1)
out = tf.multiply(a, b)

out.eval(session=tf.compat.v1.Session())    
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

See also TF 2.0 Symbols Map for a mapping of the old API to the new one.


回答 3

你需要:

  1. 将图像张量以某种格式(jpeg,png)编码为二进制张量
  2. 在会话中评估(运行)二进制张量
  3. 将二进制文件转换为流
  4. 饲料到PIL图像
  5. (可选)使用matplotlib显示图像

码:

import tensorflow as tf
import matplotlib.pyplot as plt
import PIL

...

image_tensor = <your decoded image tensor>
jpeg_bin_tensor = tf.image.encode_jpeg(image_tensor)

with tf.Session() as sess:
    # display encoded back to image data
    jpeg_bin = sess.run(jpeg_bin_tensor)
    jpeg_str = StringIO.StringIO(jpeg_bin)
    jpeg_image = PIL.Image.open(jpeg_str)
    plt.imshow(jpeg_image)

这对我有用。您可以在ipython笔记本中尝试。只是不要忘记添加以下行:

%matplotlib inline

You need to:

  1. encode the image tensor in some format (jpeg, png) to binary tensor
  2. evaluate (run) the binary tensor in a session
  3. turn the binary to stream
  4. feed to PIL image
  5. (optional) displaythe image with matplotlib

Code:

import tensorflow as tf
import matplotlib.pyplot as plt
import PIL

...

image_tensor = <your decoded image tensor>
jpeg_bin_tensor = tf.image.encode_jpeg(image_tensor)

with tf.Session() as sess:
    # display encoded back to image data
    jpeg_bin = sess.run(jpeg_bin_tensor)
    jpeg_str = StringIO.StringIO(jpeg_bin)
    jpeg_image = PIL.Image.open(jpeg_str)
    plt.imshow(jpeg_image)

This worked for me. You can try it in a ipython notebook. Just don’t forget to add the following line:

%matplotlib inline

回答 4

也许您可以尝试一下,这种方法:

import tensorflow as tf
W1 = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
array = W1.eval(sess)
print (array)

Maybe you can try,this method:

import tensorflow as tf
W1 = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
array = W1.eval(sess)
print (array)

回答 5

在张量表示(对抗性)图像的特定情况下,我已经面对并解决了张量- > ndarray转换,这些情况是通过cleverhans库/教程获得的。

我认为我的问题/答案(在此处)对于其他情况也可能是一个有用的示例。

我是TensorFlow的新手,我的结论是:

似乎tensor.eval()方法可能还需要输入占位符的值才能成功。张量可能像需要feed_dict返回输入值(提供)的函数一样工作,例如返回

array_out = tensor.eval(session=sess, feed_dict={x: x_input})

请注意,在我的情况下,占位符名称为x,但我想您应该为输入的占位符找出正确的名称。 x_input is a scalar value or array containing input data.

就我而言,提供sess也是强制性的。

我的示例还涵盖了matplotlib图像可视化部分,但这是OT。

I have faced and solved the tensor->ndarray conversion in the specific case of tensors representing (adversarial) images, obtained with cleverhans library/tutorials.

I think that my question/answer (here) may be an helpful example also for other cases.

I’m new with TensorFlow, mine is an empirical conclusion:

It seems that tensor.eval() method may need, in order to succeed, also the value for input placeholders. Tensor may work like a function that needs its input values (provided into feed_dict) in order to return an output value, e.g.

array_out = tensor.eval(session=sess, feed_dict={x: x_input})

Please note that the placeholder name is x in my case, but I suppose you should find out the right name for the input placeholder. x_input is a scalar value or array containing input data.

In my case also providing sess was mandatory.

My example also covers the matplotlib image visualization part, but this is OT.


回答 6

一个简单的例子可能是

    import tensorflow as tf
    import numpy as np
    a=tf.random_normal([2,3],0.0,1.0,dtype=tf.float32)  #sampling from a std normal
    print(type(a))
    #<class 'tensorflow.python.framework.ops.Tensor'>
    tf.InteractiveSession()  # run an interactive session in Tf.

n现在,如果我们希望将张量a转换为numpy数组

    a_np=a.eval()
    print(type(a_np))
    #<class 'numpy.ndarray'>

就如此容易!

A simple example could be,

    import tensorflow as tf
    import numpy as np
    a=tf.random_normal([2,3],0.0,1.0,dtype=tf.float32)  #sampling from a std normal
    print(type(a))
    #<class 'tensorflow.python.framework.ops.Tensor'>
    tf.InteractiveSession()  # run an interactive session in Tf.

n now if we want this tensor a to be converted into a numpy array

    a_np=a.eval()
    print(type(a_np))
    #<class 'numpy.ndarray'>

As simple as that!


回答 7

我正在寻找此命令的日子。

在任何会议或类似活动之外,这对我都有效。

# you get an array = your tensor.eval(session=tf.compat.v1.Session())
an_array = a_tensor.eval(session=tf.compat.v1.Session())

https://kite.com/python/answers/how-to-convert-a-tensorflow-tensor-to-a-numpy-array-in-python

I was searching for days for this command.

This worked for me outside any session or somthing like this.

# you get an array = your tensor.eval(session=tf.compat.v1.Session())
an_array = a_tensor.eval(session=tf.compat.v1.Session())

https://kite.com/python/answers/how-to-convert-a-tensorflow-tensor-to-a-numpy-array-in-python


回答 8

您可以使用keras后端功能。

import tensorflow as tf
from tensorflow.python.keras import backend 

sess = backend.get_session()
array = sess.run(< Tensor >)

print(type(array))

<class 'numpy.ndarray'>

希望对您有所帮助!

You can use keras backend function.

import tensorflow as tf
from tensorflow.python.keras import backend 

sess = backend.get_session()
array = sess.run(< Tensor >)

print(type(array))

<class 'numpy.ndarray'>

I hope it helps!


找不到满足需求张量流的版本

问题:找不到满足需求张量流的版本

我安装了最新版本的Python (3.6.4 64-bit)和最新版本的PyCharm (2017.3.3 64-bit)。然后我在PyCharm中安装了一些模块(Numpy,Pandas等),但是当我尝试安装Tensorflow时却没有安装,并且出现了错误消息:

找不到满足TensorFlow要求的版本(来自版本:)找不到与TensorFlow匹配的发行版。

然后我尝试从命令提示符下安装TensorFlow,并得到了相同的错误消息。但是,我确实成功安装了tflearn。

我还安装了Python 2.7,但又收到了相同的错误消息。我搜索了该错误,并尝试了一些建议给其他人的方法,但是没有任何效果(包括安装Flask)。

我该如何安装Tensorflow?谢谢。

I installed the latest version of Python (3.6.4 64-bit) and the latest version of PyCharm (2017.3.3 64-bit). Then I installed some modules in PyCharm (Numpy, Pandas, etc), but when I tried installing Tensorflow it didn’t install, and I got the error message:

Could not find a version that satisfies the requirement TensorFlow (from versions: ) No matching distribution found for TensorFlow.

Then I tried installing TensorFlow from the command prompt and I got the same error message. I did however successfully install tflearn.

I also installed Python 2.7, but I got the same error message again. I googled the error and tried some of the things which were suggested to other people, but nothing worked (this included installing Flask).

How can I install Tensorflow? Thanks.


回答 0

截至2018年8月13日的Tensorflow支持Python 3.6.x和仅64位版本。

As of October 2020:

  • Tensorflow only supports the 64-bit version of Python

  • Tensorflow only supports Python 3.5 to 3.8

So, if you’re using an out-of-range version of Python (older or newer) or a 32-bit version, then you’ll need to use a different version.


回答 1

安装Tensorflow有两个重要规则:

  • 您必须安装Python x64。它在32b上不起作用,并且给出与您相同的错误。

  • 支持最新版本的Python3 = 3.7。

例如,您可以安装Python3.6.2-64bit,它的工作原理类似于Charm。

更新资料

据说在评论中,它可以在x64版本的Python3.8中使用。

There are a few important rules to install Tensorflow:

  • You have to install Python x64. It doesn’t work on 32b and it gives the same error as yours.

  • It doesn’t support Python versions later than 3.8 and Python 3.8 requires TensorFlow 2.2 or later.

For example, you can install Python3.8.6-64bit and it works like a charm.


回答 2

我成功安装了 pip install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl

I installed it successfully by pip install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl


回答 3

如果您使用anaconda,则默认情况下会安装python 3.7,因此您必须将其降级为3.6:

康达安装python = 3.6

然后:

点安装tensorflow

它在Ubuntu中为我工作。

if you are using anaconda, python 3.7 is installed by default, so you have to downgrade it to 3.6:

conda install python=3.6

then:

pip install tensorflow

it worked for me in Ubuntu.


回答 4

我正在为Windows提供它

如果您使用的是python-3

  1. 使用以下命令将pip升级到最新版本 py -m pip install --upgrade pip
  2. 使用安装软件包 py -m pip install <package-name>

如果您使用的是python-2

  1. 使用以下命令将pip升级到最新版本 py -2 -m pip install --upgrade pip
  2. 使用安装软件包 py -2 -m pip install <package-name>

对我有用

I am giving it for Windows

If you are using python-3

  1. Upgrade pip to the latest version using py -m pip install --upgrade pip
  2. Install package using py -m pip install <package-name>

If you are using python-2

  1. Upgrade pip to the latest version using py -2 -m pip install --upgrade pip
  2. Install package using py -2 -m pip install <package-name>

It worked for me


回答 5

根据Tensorflow python 3.8文档页面(截至2019年12月4日),该版本不可用。您将必须降级到python 3.7

Tensorflow isn’t available for python 3.8 (as of Dec 4th 2019) according to their documentation page. You will have to downgrade to python 3.7.


回答 6

卸载Python然后重新安装解决了我的问题,并且我能够成功安装TensorFlow。

Uninstalling Python and then reinstalling solved my issue and I was able to successfully install TensorFlow.


回答 7

不支持Python版本卸载python

https://www.python.org/downloads/release/python-362/

您应该在安装页面中检查并使用确切的版本。 https://www.tensorflow.org/install/install_windows

python 3.6.2或python 3.5.2为我解决了这个问题

Python version is not supported Uninstall python

https://www.python.org/downloads/release/python-362/

You should check and use the exact version in install page. https://www.tensorflow.org/install/install_windows

python 3.6.2 or python 3.5.2 solved this issue for me


回答 8

Tensorflow 2.2.0支持Python3.8

首先,请确保安装Python 3.8 64bit。出于某种原因,官方网站默认为32位。使用python -VV(两个大写字母V,不是W)验证此内容。然后照常继续:

python -m pip install --upgrade pip
python -m pip install wheel  # not necessary
python -m pip install tensorflow

与往常一样,请确保已安装CUDA 10.1和CuDNN。

Tensorflow 2.2.0 supports Python3.8

First, make sure to install Python 3.8 64bit. For some reason, the official site defaults to 32bit. Verify this using python -VV (two capital V, not W). Then continue as usual:

python -m pip install --upgrade pip
python -m pip install wheel  # not necessary
python -m pip install tensorflow

As usual, make sure you have CUDA 10.1 and CuDNN installed.


回答 9

看起来问题出在Python 3.8。请改用Python 3.7。我已采取步骤解决此问题。

  • 使用conda创建了python 3.7环境
  • 列表项在环境中使用pip install rasa安装了rasa。

为我工作。

Looks like the problem is with Python 3.8. Use Python 3.7 instead. Steps I took to solve this.

  • Created a python 3.7 environment with conda
  • List item Installed rasa using pip install rasa within the environment.

Worked for me.


回答 10

我在ubunu 18.04上使用python 3.6.8,对我来说解决方案是只升级pip

pip install --upgrade pip
pip install tensorflow==2.1.0

I am using python 3.6.8, on ubunu 18.04, for me the solution was to just upgrade pip

pip install --upgrade pip
pip install tensorflow==2.1.0

回答 11

Tensorflow似乎需要特殊版本的工具和库。Pip仅负责python版本。

要以专业的方式处理此问题(意味着它为我和其他人节省了Tremendos的时间),您必须为每个这样的软件设置一个特殊的环境。

为此,conda是一种高级工具。

我使用以下命令安装了Tensorflow:

sudo apt安装python3

sudo update-alternatives –install / usr / bin / python python / usr / bin / python3 1

sudo apt安装python3-pip

须藤apt-get install curl

卷曲https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh > Miniconda3-latest-Linux-x86_64.sh

bash Miniconda3-最新-Linux-x86_64.sh

来源〜/ .bashrc

  • 安装自己的phyton等

纳米.bashrc

  • 也许在这里插入您的代理等。

conda创建–name your_name python = 3

conda激活your_name

conda安装-c conda-forge tensorflow

  • 检查一切顺利

python -c“将tensorflow导入为tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000,1000])))”“

PS:一些可能有助于conda搜索tensorflow的命令

https://www.tensorflow.org/install/pip

使用virtualenv。康达更胜任。迷你主义者就足够了;不需要完整的conda

Tensorflow seems to need special versions of tools and libs. Pip only takes care of python version.

To handle this in a professional way (means it save tremendos time for me and others) you have to set a special environment for each software like this.

An advanced tool for this is conda.

I installed Tensorflow with this commands:

sudo apt install python3

sudo update-alternatives –install /usr/bin/python python /usr/bin/python3 1

sudo apt install python3-pip

sudo apt-get install curl

curl https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh > Miniconda3-latest-Linux-x86_64.sh

bash Miniconda3-latest-Linux-x86_64.sh

yes

source ~/.bashrc

  • installs its own phyton etc

nano .bashrc

  • maybe insert here your proxies etc.

conda create –name your_name python=3

conda activate your_name

conda install -c conda-forge tensorflow

  • check everything went well

python -c “import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))”

PS: some commands that may be helpful conda search tensorflow

https://www.tensorflow.org/install/pip

uses virtualenv. Conda is more capable. Miniconda ist sufficient; the full conda is not necessary


回答 12

tensorflow安装为我解决之前运行此命令:

pip install "pip>=19"

正如tensorflow的系统要求所述:

点19.0或更高版本

Running this before the tensorflow installation solved it for me:

pip install "pip>=19"

As the tensorflow‘s system requirements states:

pip 19.0 or later


回答 13

使用python 3.6或3.7版本,但重要的是您应该安装python版本的64位。

use python version 3.6 or 3.7 but the important thing is you should install the python version of 64-bit.


回答 14

对于TensorFlow 2.2版本:

  1. 确保您拥有python 3.8

尝试: python --version

要么 python3 --version

要么 py --version

  1. 升级python版本3.8的pip

尝试: python3 -m pip install --upgrade pip

要么 python -m pip install --upgrade pip

要么 py -m pip install --upgrade pip

  1. 安装TensorFlow:

尝试: python3 -m pip install TensorFlow

要么 python -m pip install TensorFlow

要么 py -m pip install TensorFlow

  1. 确保使用正确的python运行文件:

尝试: python3 file.py

要么 python file.py

要么 py file.py

For version TensorFlow 2.2:

  1. Make sure you have python 3.8

try: python --version

or python3 --version

or py --version

  1. Upgrade the pip of the python which has version 3.8

try: python3 -m pip install --upgrade pip

or python -m pip install --upgrade pip

or py -m pip install --upgrade pip

  1. Install TensorFlow:

try: python3 -m pip install TensorFlow

or python -m pip install TensorFlow

or py -m pip install TensorFlow

  1. Make sure to run the file with the correct python:

try: python3 file.py

or python file.py

or py file.py


回答 15

通过一一安装所需的所有软件包,我解决了与python 3.7相同的问题

步骤如下:

  1. 安装套件
  2. 请参阅错误消息:

    找不到满足要求的版本-所需模块的名称

  3. 安装所需的模块。通常,安装所需的模块需要安装另一个模块,以及另一个模块-其他两个模块,依此类推。

这样,我安装了30多个软件包,并有所帮助。现在我有了python 3.7中最新版本的tensorflow,而不必降级内核。

I solved the same problem with python 3.7 by installing one by one all the packages required

Here are the steps:

  1. Install the package
  2. See the error message:

    couldn’t find a version that satisfies the requirement — the name of the module required

  3. Install the module required. Very often, installation of the required module requires the installation of another module, and another module – a couple of the others and so on.

This way I installed more than 30 packages and it helped. Now I have tensorflow of the latest version in Python 3.7 and didn’t have to downgrade the kernel.


Autokeras-面向深度学习的AutoML库

logo

官网:autokeras.com

AutoKera:一个基于KERS的AutoML系统。它是由DATA Lab在德克萨斯农工大学。AutoKera的目标是让每个人都可以使用机器学习

学习资源

  • 一个简短的例子

import autokeras as ak

clf = ak.ImageClassifier()
clf.fit(x_train, y_train)
results = clf.predict(x_test)

drawing

安装

要安装该软件包,请使用pip安装步骤如下:

pip3 install autokeras

请按照installation guide有关更多详细信息,请参阅

注:目前,AutoKera仅与Python>=3.5TensorFlow>=2.3.0

社区

随时了解最新信息

推特:你也可以在推特上关注我们@autokeras了解最新消息

电子邮件:订阅我们的email list接收通知的步骤

问题和讨论

GitHub讨论:请在我们的GitHub Discussions这是一个在GitHub上托管的论坛。我们将在那里监控并回答问题

即时通信

松弛Request an invitation使用#autokeras通信通道

QQ群:加入我们的QQ群1150366085。密码:akqqgroup

在线会议:加入online meeting Google group日历事件将出现在您的Google日历上

贡献代码

我们致力于让AutoKera的一切向公众开放。每个人都可以很容易地以开发人员的身份加入。以下是我们如何管理我们的项目

  • 对问题进行分类例如,我们从中挑选要解决的关键问题GitHub issues它们将被添加到此Project其中一些问题随后将添加到milestones,用于计划发布
  • 分配任务:我们在网上会议期间将任务分配给人们
  • 讨论:我们可以在多个地方进行讨论。代码审查在GitHub上。问题可以在Slake或在会议期间提问

请加入我们的Slack给金海峰发个口信。或顺道拜访我们的online meetings然后跟我们谈谈。我们将帮助您入门!

请参阅我们的Contributing Guide学习最佳实践

感谢所有的贡献者!

捐赠

我们接受财政上的支持Open Collective感谢每一位赞助商对我们的支持!


引用这部作品

金海峰、宋清泉、夏虎。“Auto-keras:一种高效的神经结构搜索系统。”第25届ACM SIGKDD知识发现与数据挖掘国际会议论文集。ACM,2019年。(Download)

Biblatex条目:

@inproceedings{jin2019auto,
  title={Auto-Keras: An Efficient Neural Architecture Search System},
  author={Jin, Haifeng and Song, Qingquan and Hu, Xia},
  booktitle={Proceedings of the 25th ACM SIGKDD International Conference on Knowledge Discovery \& Data Mining},
  pages={1946--1956},
  year={2019},
  organization={ACM}
}

确认

作者感谢国防高级研究计划局(DARPA)通过AFRL合同FA8750-17-2-0116、德克萨斯农工学院和德克萨斯农工大学管理的D3M计划

Tensorlayer-面向科学家和工程师的深度学习和强化学习库🔥

TensorLayer是一个为研究人员和工程师设计的基于TensorFlow的深度学习和强化学习库。它提供了大量的可定制的神经层来快速构建高级的AI模型,在此基础上,社区开源的MASStutorialsapplicationsTensorLayer荣获2017年度最佳开源软件奖ACM Multimedia Society该项目也可以在iHubGitee

新闻

🔥3.0.0将支持多个后端,如TensorFlow、MindSporte、PaddlePaddle等,允许用户在NVIDIA-GPU和华为-Ascend等不同硬件上运行代码。我们需要更多的人加入开发团队,如果你感兴趣,请发电子邮件hao.dong@pku.edu.cn

🔥强化学习动物园:Low-level APIs对于专业用途,High-level APIs对于简单的用法,以及相应的Springer textbook

🔥Sipeed Maxi-EMC:在上运行TensorLayer模型一种低成本的AI芯片(例如K210)(Alpha版本)

设计特点

TensorLayer是一个全新的深度学习库,其设计考虑到了简单性、灵活性和高性能

  • 简单性:TensorLayer具有易于学习的高级层/模型抽象。您可以在几分钟内了解深度学习如何为您的人工智能任务带来好处,通过海量的examples
  • 灵活性:TensorLayer API是透明和灵活的,灵感来自新兴的PyTorch库。与KERAS抽象相比,TensorLayer使构建和训练复杂的AI模型变得容易得多
  • 零成本抽象:虽然使用起来很简单,但TensorLayer并不要求您在TensorFlow的性能上做出任何妥协(有关更多详细信息,请查看以下基准测试部分)

TensorLayer位于TensorFlow包装器中的一个独特位置。其他包装器,如Kera和TFLearn,隐藏了TensorFlow的许多强大功能,并且对编写自定义AI模型几乎没有提供支持。受到PyTorch的启发,TensorLayer API简单、灵活、Pythonic,让学习变得轻松,同时足够灵活地应对复杂的AI任务。TensorLayer拥有一个快速增长的社区。它已经被世界各地的研究人员和工程师使用,包括来自北京大学、伦敦帝国理工学院、加州大学伯克利分校、卡内基梅隆大学、斯坦福大学的研究人员和工程师,以及谷歌、微软、阿里巴巴、腾讯、小米和彭博社等公司的研究人员和工程师

多语种文档

TensorLayer为初学者和专业人士提供了大量文档。该文档有英文和中文两种版本。

English Documentation
Chinese Documentation
Chinese Book

如果您想在主分支上尝试实验功能,可以找到最新的文档here

大量的例子

中可以找到大量使用TensorLayer的示例here以及以下空格:

快速入门

TensorLayer2.0依赖于TensorFlow、Numpy等。要使用GPU,需要CUDA和cuDNN

安装TensorFlow:

pip3 install tensorflow-gpu==2.0.0-rc1 # TensorFlow GPU (version 2.0 RC1)
pip3 install tensorflow # CPU version

安装稳定版本的TensorLayer:

pip3 install tensorlayer

安装TensorLayer的不稳定开发版本:

pip3 install git+https://github.com/tensorlayer/tensorlayer.git

如果要安装其他依赖项,还可以运行

pip3 install --upgrade tensorlayer[all]              # all additional dependencies
pip3 install --upgrade tensorlayer[extra]            # only the `extra` dependencies
pip3 install --upgrade tensorlayer[contrib_loggers]  # only the `contrib_loggers` dependencies

如果您是TensorFlow 1.X用户,则可以使用TensorLayer 1.11.0:

# For last stable version of TensorLayer 1.X
pip3 install --upgrade tensorlayer==1.11.0

性能基准

下表显示了以下各项的训练速度VGG16在Titan XP上使用TensorLayer和原生TensorFlow

模式 Lib 数据格式 最大GPU内存使用量(MB) 最大CPU内存使用量(MB) 平均CPU内存使用率(MB) 运行时间(秒)
亲笔签名 TensorFlow 2.0 最后一个频道 11833 2161 2136 74
TensorLayer 2.0 最后一个频道 11833 2187 2169 76
图表 凯拉斯 最后一个频道 8677 2580 2576 101
渴望 TensorFlow 2.0 最后一个频道 8723 2052年 2024年 97
TensorLayer 2.0 最后一个频道 8723 2010年 2007年 95

参与其中

请阅读Contributor Guideline在提交您的请购单之前

我们建议用户使用Github问题报告错误。用户还可以讨论如何在以下空闲通道中使用TensorLayer

引用TensorLayer

如果您觉得TensorLayer对您的项目有用,请引用以下论文:

@article{tensorlayer2017,
    author  = {Dong, Hao and Supratak, Akara and Mai, Luo and Liu, Fangde and Oehmichen, Axel and Yu, Simiao and Guo, Yike},
    journal = {ACM Multimedia},
    title   = {{TensorLayer: A Versatile Library for Efficient Deep Learning Development}},
    url     = {http://tensorlayer.org},
    year    = {2017}
}

@inproceedings{tensorlayer2021,
  title={Tensorlayer 3.0: A Deep Learning Library Compatible With Multiple Backends},
  author={Lai, Cheng and Han, Jiarong and Dong, Hao},
  booktitle={2021 IEEE International Conference on Multimedia \& Expo Workshops (ICMEW)},
  pages={1--3},
  year={2021},
  organization={IEEE}
}

如何防止张量流分配GPU内存的总量?

问题:如何防止张量流分配GPU内存的总量?

我在共享计算资源的环境中工作,即,我们有几台服务器计算机,每台服务器计算机都配备了一些Nvidia Titan X GPU。

对于中小型型号,Titan X的12 GB通常足以让2-3个人在同一GPU上同时进行训练。如果模型足够小,以至于单个模型无法充分利用GPU的所有计算单元,那么与运行一个训练过程之后再执行另一个训练过程相比,这实际上可以提高速度。即使在同时访问GPU确实减慢了单个训练时间的情况下,具有让多个用户同时在GPU上进行训练的灵活性仍然很好。

TensorFlow的问题在于,默认情况下,它在启动时会分配全部可用的GPU内存。即使对于小型的两层神经网络,我也看到所有12 GB的GPU内存都已用完。

如果有人知道这足以满足给定模型的需求,是否有办法使TensorFlow仅分配4 GB的GPU内存?

I work in an environment in which computational resources are shared, i.e., we have a few server machines equipped with a few Nvidia Titan X GPUs each.

For small to moderate size models, the 12 GB of the Titan X is usually enough for 2–3 people to run training concurrently on the same GPU. If the models are small enough that a single model does not take full advantage of all the computational units of the GPU, this can actually result in a speedup compared with running one training process after the other. Even in cases where the concurrent access to the GPU does slow down the individual training time, it is still nice to have the flexibility of having multiple users simultaneously train on the GPU.

The problem with TensorFlow is that, by default, it allocates the full amount of available GPU memory when it is launched. Even for a small two-layer neural network, I see that all 12 GB of the GPU memory is used up.

Is there a way to make TensorFlow only allocate, say, 4 GB of GPU memory, if one knows that this is enough for a given model?


回答 0

您可以tf.Session通过传递a tf.GPUOptions作为可选config参数的一部分来设置构造a时要分配的GPU内存的比例:

# Assume that you have 12GB of GPU memory and want to allocate ~4GB:
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)

sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

per_process_gpu_memory_fraction是同一台计算机上每个GPU上的进程将使用的GPU内存量的硬上限。当前,这部分被均匀地应用于同一台机器上的所有GPU。无法基于每个GPU进行设置。

You can set the fraction of GPU memory to be allocated when you construct a tf.Session by passing a tf.GPUOptions as part of the optional config argument:

# Assume that you have 12GB of GPU memory and want to allocate ~4GB:
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)

sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

The per_process_gpu_memory_fraction acts as a hard upper bound on the amount of GPU memory that will be used by the process on each GPU on the same machine. Currently, this fraction is applied uniformly to all of the GPUs on the same machine; there is no way to set this on a per-GPU basis.


回答 1

config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)

https://github.com/tensorflow/tensorflow/issues/1578

config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)

https://github.com/tensorflow/tensorflow/issues/1578


回答 2

这是本书的摘录 Deep Learning with TensorFlow

在某些情况下,希望该过程仅分配可用内存的子集,或者仅增加该过程所需的内存使用量。TensorFlow 在会话中提供了两个配置选项来控制它。第一个是该allow_growth选项,它尝试根据运行时分配仅分配尽可能多的GPU内存,它开始时分配的内存很少,并且随着会话的运行和需要更多GPU内存,我们扩展了TensorFlow所需的GPU内存区域处理。

1)允许增长:(更灵活)

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config, ...)

第二种方法是per_process_gpu_memory_fraction选项,它确定each应分配可见GPU 的内存总量的一部分。注意:不需要释放内存,完成后甚至会加剧内存碎片。

2)分配固定内存

仅通过以下方式分配40%每个GPU的总内存:

config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.4
session = tf.Session(config=config, ...)

注意: 这仅在您真正想绑定TensorFlow进程上可用的GPU内存量时有用。

Here is an excerpt from the Book Deep Learning with TensorFlow

In some cases it is desirable for the process to only allocate a subset of the available memory, or to only grow the memory usage as it is needed by the process. TensorFlow provides two configuration options on the session to control this. The first is the allow_growth option, which attempts to allocate only as much GPU memory based on runtime allocations, it starts out allocating very little memory, and as sessions get run and more GPU memory is needed, we extend the GPU memory region needed by the TensorFlow process.

1) Allow growth: (more flexible)

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config, ...)

The second method is per_process_gpu_memory_fraction option, which determines the fraction of the overall amount of memory that each visible GPU should be allocated. Note: No release of memory needed, it can even worsen memory fragmentation when done.

2) Allocate fixed memory:

To only allocate 40% of the total memory of each GPU by:

config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.4
session = tf.Session(config=config, ...)

Note: That’s only useful though if you truly want to bind the amount of GPU memory available on the TensorFlow process.


回答 3

已针对TensorFlow 2.0 Alpha及更高版本进行了更新

从2.0 Alpha文档来看,答案现在只有一行,然后您可以使用TensorFlow进行任何操作:

import tensorflow as tf
tf.config.gpu.set_per_process_memory_growth(True)

For TensorFlow 2.0 and 2.1 (docs):

import tensorflow as tf
tf.config.gpu.set_per_process_memory_growth(True)

For TensorFlow 2.2+ (docs):

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
  tf.config.experimental.set_memory_growth(gpu, True)

The docs also list some more methods:

  • Set environment variable TF_FORCE_GPU_ALLOW_GROWTH to true.
  • Use tf.config.experimental.set_virtual_device_configuration to set a hard limit on a Virtual GPU device.

回答 4

以上所有答案均假定通过sess.run()调用执行,这已成为exceptions,而不是TensorFlow的最新版本中的规则。

使用tf.Estimator框架(TensorFlow 1.4及更高版本)时,将分数传递给隐式创建的方法MonitoredTrainingSession是:

opts = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
conf = tf.ConfigProto(gpu_options=opts)
trainingConfig = tf.estimator.RunConfig(session_config=conf, ...)
tf.estimator.Estimator(model_fn=..., 
                       config=trainingConfig)

同样在“急切”模式(TensorFlow 1.5及更高版本)中,

opts = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
conf = tf.ConfigProto(gpu_options=opts)
tfe.enable_eager_execution(config=conf)

编辑:11-04-2018 作为示例,如果要使用tf.contrib.gan.train,则可以使用类似于波纹管的东西:

tf.contrib.gan.gan_train(........, config=conf)

All the answers above assume execution with a sess.run() call, which is becoming the exception rather than the rule in recent versions of TensorFlow.

When using the tf.Estimator framework (TensorFlow 1.4 and above) the way to pass the fraction along to the implicitly created MonitoredTrainingSession is,

opts = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
conf = tf.ConfigProto(gpu_options=opts)
trainingConfig = tf.estimator.RunConfig(session_config=conf, ...)
tf.estimator.Estimator(model_fn=..., 
                       config=trainingConfig)

Similarly in Eager mode (TensorFlow 1.5 and above),

opts = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
conf = tf.ConfigProto(gpu_options=opts)
tfe.enable_eager_execution(config=conf)

Edit: 11-04-2018 As an example, if you are to use tf.contrib.gan.train, then you can use something similar to bellow:

tf.contrib.gan.gan_train(........, config=conf)

回答 5

对于Tensorflow版本2.0和2.1使用以下代码段

 import tensorflow as tf
 gpu_devices = tf.config.experimental.list_physical_devices('GPU')
 tf.config.experimental.set_memory_growth(gpu_devices[0], True)

对于以前的版本,以下代码段对我有用:

import tensorflow as tf
tf_config=tf.ConfigProto()
tf_config.gpu_options.allow_growth=True
sess = tf.Session(config=tf_config)

For Tensorflow version 2.0 and 2.1 use the following snippet:

 import tensorflow as tf
 gpu_devices = tf.config.experimental.list_physical_devices('GPU')
 tf.config.experimental.set_memory_growth(gpu_devices[0], True)

For prior versions , following snippet used to work for me:

import tensorflow as tf
tf_config=tf.ConfigProto()
tf_config.gpu_options.allow_growth=True
sess = tf.Session(config=tf_config)

回答 6

Tensorflow 2.0 Beta和(可能)超越

API再次更改。现在可以在以下位置找到它:

tf.config.experimental.set_memory_growth(
    device,
    enable
)

别名:

  • tf.compat.v1.config.experimental.set_memory_growth
  • tf.compat.v2.config.experimental.set_memory_growth

参考文献:

另请参阅: Tensorflow-使用GPUhttps : //www.tensorflow.org/guide/gpu

对于Tensorflow 2.0 Alpha,请参阅: 此答案

Tensorflow 2.0 Beta and (probably) beyond

The API changed again. It can be now found in:

tf.config.experimental.set_memory_growth(
    device,
    enable
)

Aliases:

  • tf.compat.v1.config.experimental.set_memory_growth
  • tf.compat.v2.config.experimental.set_memory_growth

References:

See also: Tensorflow – Use a GPU: https://www.tensorflow.org/guide/gpu

for Tensorflow 2.0 Alpha see: this answer


回答 7

您可以使用

TF_FORCE_GPU_ALLOW_GROWTH=true

在您的环境变量中。

在张量代码中:

bool GPUBFCAllocator::GetAllowGrowthValue(const GPUOptions& gpu_options) {
  const char* force_allow_growth_string =
      std::getenv("TF_FORCE_GPU_ALLOW_GROWTH");
  if (force_allow_growth_string == nullptr) {
    return gpu_options.allow_growth();
}

You can use

TF_FORCE_GPU_ALLOW_GROWTH=true

in your environment variables.

In tensorflow code:

bool GPUBFCAllocator::GetAllowGrowthValue(const GPUOptions& gpu_options) {
  const char* force_allow_growth_string =
      std::getenv("TF_FORCE_GPU_ALLOW_GROWTH");
  if (force_allow_growth_string == nullptr) {
    return gpu_options.allow_growth();
}

回答 8

无耻插件:如果安装了GPU支持的Tensorflow,则无论您将其设置为仅使用CPU还是GPU,该会话都会首先分配所有GPU。我可能会补充一点,即使您将图形设置为仅使用CPU,也应该设置相同的配置(如上回答:)),以防止不必要的GPU占用。

并且在类似IPython的交互式界面中,您还应该设置configure,否则它将分配所有内存,而几乎不分配给其他人。有时很难注意到。

Shameless plug: If you install the GPU supported Tensorflow, the session will first allocate all GPU whether you set it to use only CPU or GPU. I may add my tip that even you set the graph to use CPU only you should set the same configuration(as answered above:) ) to prevent the unwanted GPU occupation.

And in an interactive interface like IPython and Jupyter, you should also set that configure, otherwise, it will allocate all memory and left almost none for others. This is sometimes hard to notice.


回答 9

对于Tensorflow 2.0而言,解决方案适用于我。(TF-GPU 2.0,Windows 10,GeForce RTX 2070)

physical_devices = tf.config.experimental.list_physical_devices('GPU')
assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
tf.config.experimental.set_memory_growth(physical_devices[0], True)

For Tensorflow 2.0 this this solution worked for me. (TF-GPU 2.0, Windows 10, GeForce RTX 2070)

physical_devices = tf.config.experimental.list_physical_devices('GPU')
assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
tf.config.experimental.set_memory_growth(physical_devices[0], True)

回答 10

如果您使用的是Tensorflow 2,请尝试以下操作:

config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.Session(config=config)

If you’re using Tensorflow 2 try the following:

config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.Session(config=config)

回答 11

我尝试对voc数据集进行unet训练,但是由于巨大的图像大小,内存完成了。我尝试了上述所有技巧,甚至尝试使用批处理大小== 1,但没有任何改善。有时TensorFlow版本也会导致内存问题。尝试使用

点安装tensorflow-gpu == 1.8.0

i tried to train unet on voc data set but because of huge image size, memory finishes. i tried all the above tips, even tried with batch size==1, yet to no improvement. sometimes TensorFlow version also causes the memory issues. try by using

pip install tensorflow-gpu==1.8.0


回答 12

好吧,我是tensorflow的新手,我有Geforce 740m或具有2GB内存的GPU,我正在运行mnist手写的本地语言示例,其训练数据包含38700张图像和4300张测试图像,并试图获得精度,召回率, F1使用以下代码作为sklearn并没有给我精确的结果。一旦将其添加到现有代码中,我就开始出现GPU错误。

TP = tf.count_nonzero(predicted * actual)
TN = tf.count_nonzero((predicted - 1) * (actual - 1))
FP = tf.count_nonzero(predicted * (actual - 1))
FN = tf.count_nonzero((predicted - 1) * actual)

prec = TP / (TP + FP)
recall = TP / (TP + FN)
f1 = 2 * prec * recall / (prec + recall)

再加上我的模型很沉重,我想我在147个,148个纪元后出现内存错误,然后我想为什么不为这些任务创建函数,所以我不知道它是否在tensrorflow中以这种方式工作,但是我想如果局部变量是使用,并且超出范围可能释放内存,并且我在模块中定义了用于培训和测试的上述元素,我能够实现10000个纪元而没有任何问题,希望对您有所帮助。

Well I am new to tensorflow, I have Geforce 740m or something GPU with 2GB ram, I was running mnist handwritten kind of example for a native language with training data containing of 38700 images and 4300 testing images and was trying to get precision , recall , F1 using following code as sklearn was not giving me precise reults. once i added this to my existing code i started getting GPU errors.

TP = tf.count_nonzero(predicted * actual)
TN = tf.count_nonzero((predicted - 1) * (actual - 1))
FP = tf.count_nonzero(predicted * (actual - 1))
FN = tf.count_nonzero((predicted - 1) * actual)

prec = TP / (TP + FP)
recall = TP / (TP + FN)
f1 = 2 * prec * recall / (prec + recall)

plus my model was heavy i guess, i was getting memory error after 147, 148 epochs, and then I thought why not create functions for the tasks so I dont know if it works this way in tensrorflow, but I thought if a local variable is used and when out of scope it may release memory and i defined the above elements for training and testing in modules, I was able to achieve 10000 epochs without any issues, I hope this will help..


回答 13

# allocate 60% of GPU memory 
from keras.backend.tensorflow_backend import set_session
import tensorflow as tf 
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.6
set_session(tf.Session(config=config))
# allocate 60% of GPU memory 
from keras.backend.tensorflow_backend import set_session
import tensorflow as tf 
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.6
set_session(tf.Session(config=config))

如何在TensorFlow中打印Tensor对象的值?

问题:如何在TensorFlow中打印Tensor对象的值?

我一直在使用TensorFlow中矩阵乘法的入门示例。

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

当我打印产品时,它会将其显示为Tensor对象:

<tensorflow.python.framework.ops.Tensor object at 0x10470fcd0>

但是我怎么知道的价值product呢?

以下内容无济于事:

print product
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=float32)

我知道图形可以继续运行Sessions,但是没有任何方法可以在Tensor不运行图形的情况下检查对象的输出session吗?

I have been using the introductory example of matrix multiplication in TensorFlow.

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

When I print the product, it is displaying it as a Tensor object:

<tensorflow.python.framework.ops.Tensor object at 0x10470fcd0>

But how do I know the value of product?

The following doesn’t help:

print product
Tensor("MatMul:0", shape=TensorShape([Dimension(1), Dimension(1)]), dtype=float32)

I know that graphs run on Sessions, but isn’t there any way I can check the output of a Tensor object without running the graph in a session?


回答 0

评估对象实际值的最简单方法[A]Tensor是将其传递给Session.run()方法,或者Tensor.eval()在有默认会话时(即在一个with tf.Session():块中,或参阅下文)调用该方法。通常[B],如果不在会话中运行某些代码,就无法打印张量的值。

如果您正在试验编程模型,并且想要一种简单的方法来评估张量,则tf.InteractiveSession可以在程序开始时打开一个会话,然后将该会话用于所有Tensor.eval()(和Operation.run())调用。当在一个Session无处不在的对象周围传递乏味的代码时,在诸如外壳或IPython笔记本之类的交互式设置中,这可能会更容易。例如,以下内容在Jupyter笔记本中起作用:

with tf.Session() as sess:  print(product.eval()) 

对于这么小的表达式来说,这似乎很愚蠢,但是Tensorflow 1.x的关键思想之一是推迟执行:构建一个大型而复杂的表达式非常便宜,并且当您要对其进行评估时,后端与您连接的Session)能够更有效地安排其执行时间(例如,并行执行独立的部分并使用GPU)。


[A]:要打印张量的值而不将其返回到Python程序,可以使用tf.print()运算符,如Andrzej在另一个答案中建议的那样。根据官方文件:

为了确保操作员能够运行,用户需要将产生的op传递给tf.compat.v1.Session的run方法,或者通过将其指定为来将op用作已执行op的控件依赖项tf.compat.v1.control_dependencies([print_op],并打印到标准输出中。

另请注意:

在Jupyter笔记本和Colab中,tf.print打印到笔记本单元的输出。它不会写入笔记本内核的控制台日志。

[B]:如果可以有效tf.get_static_value()地计算给定张量的值,则可以使用该函数获取其恒定值。

The easiest[A] way to evaluate the actual value of a Tensor object is to pass it to the Session.run() method, or call Tensor.eval() when you have a default session (i.e. in a with tf.Session(): block, or see below). In general[B], you cannot print the value of a tensor without running some code in a session.

If you are experimenting with the programming model, and want an easy way to evaluate tensors, the tf.InteractiveSession lets you open a session at the start of your program, and then use that session for all Tensor.eval() (and Operation.run()) calls. This can be easier in an interactive setting, such as the shell or an IPython notebook, when it’s tedious to pass around a Session object everywhere. For example, the following works in a Jupyter notebook:

with tf.Session() as sess:  print(product.eval()) 

This might seem silly for such a small expression, but one of the key ideas in Tensorflow 1.x is deferred execution: it’s very cheap to build a large and complex expression, and when you want to evaluate it, the back-end (to which you connect with a Session) is able to schedule its execution more efficiently (e.g. executing independent parts in parallel and using GPUs).


[A]: To print the value of a tensor without returning it to your Python program, you can use the tf.print() operator, as Andrzej suggests in another answer. According to the official documentation:

To make sure the operator runs, users need to pass the produced op to tf.compat.v1.Session‘s run method, or to use the op as a control dependency for executed ops by specifying with tf.compat.v1.control_dependencies([print_op]), which is printed to standard output.

Also note that:

In Jupyter notebooks and colabs, tf.print prints to the notebook cell outputs. It will not write to the notebook kernel’s console logs.

[B]: You might be able to use the tf.get_static_value() function to get the constant value of the given tensor if its value is efficiently calculable.


回答 1

尽管其他答案是正确的,即您不能在评估图形之前就无法打印该值,但它们并没有讨论在评估图形后在图形内部实际打印值的一种简单方法。

每当评估图形(使用runeval)时,查看张量值的最简单方法是使用Print此示例中的操作:

# Initialize session
import tensorflow as tf
sess = tf.InteractiveSession()

# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])

# Add print operation
a = tf.Print(a, [a], message="This is a: ")

# Add more elements of the graph using a
b = tf.add(a, a)

现在,无论何时我们评估整个图形,例如使用b.eval(),我们都会得到:

I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]

While other answers are correct that you cannot print the value until you evaluate the graph, they do not talk about one easy way of actually printing a value inside the graph, once you evaluate it.

The easiest way to see a value of a tensor whenever the graph is evaluated (using run or eval) is to use the Print operation as in this example:

# Initialize session
import tensorflow as tf
sess = tf.InteractiveSession()

# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])

# Add print operation
a = tf.Print(a, [a], message="This is a: ")

# Add more elements of the graph using a
b = tf.add(a, a)

Now, whenever we evaluate the whole graph, e.g. using b.eval(), we get:

I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]

回答 2

重申其他人说的话,如果不运行图形就无法检查值。

想要寻找简单示例来打印值的任何人的简单摘录如下。该代码无需修改即可在ipython Notebook中执行

import tensorflow as tf

#define a variable to hold normal random values 
normal_rv = tf.Variable( tf.truncated_normal([2,3],stddev = 0.1))

#initialize the variable
init_op = tf.initialize_all_variables()

#run the graph
with tf.Session() as sess:
    sess.run(init_op) #execute init_op
    #print the random values that we sample
    print (sess.run(normal_rv))

输出:

[[-0.16702934  0.07173464 -0.04512421]
 [-0.02265321  0.06509651 -0.01419079]]

Reiterating what others said, its not possible to check the values without running the graph.

A simple snippet for anyone looking for an easy example to print values is as below. The code can be executed without any modification in ipython notebook

import tensorflow as tf

#define a variable to hold normal random values 
normal_rv = tf.Variable( tf.truncated_normal([2,3],stddev = 0.1))

#initialize the variable
init_op = tf.initialize_all_variables()

#run the graph
with tf.Session() as sess:
    sess.run(init_op) #execute init_op
    #print the random values that we sample
    print (sess.run(normal_rv))

Output:

[[-0.16702934  0.07173464 -0.04512421]
 [-0.02265321  0.06509651 -0.01419079]]

回答 3

不,如果不运行图形,就无法看到张量的内容(这样做session.run())。您只能看到的是:

  • 张量的维数(但我认为不难为操作列表计算它) TF具有)
  • 将用于生成张量(transpose_1:0random_uniform:0
  • 张量中的元素类型(float32

我没有在文档中找到此信息,但我相信变量的值(以及某些常量在赋值时并未计算)。


看一下这个例子:

import tensorflow as tf
from datetime import datetime
dim = 7000

第一个示例中,我只是初始化一个随机数的常数Tensor,而在不显着的dim(0:00:00.003261)情况下几乎同时运行

startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
print datetime.now() - startTime

在第二种情况下,实际上是在评估常数并分配了值,时间显然取决于dim(0:00:01.244642

startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
sess = tf.Session()
sess.run(m1)
print datetime.now() - startTime

并且您可以通过计算一些东西使它更加清晰(请d = tf.matrix_determinant(m1)记住,时间将会流逝O(dim^2.8)

我发现的PS是在文档中解释的:

Tensor对象是操作结果的符号句柄,但实际上并不保存操作输出的值。

No, you can not see the content of the tensor without running the graph (doing session.run()). The only things you can see are:

  • the dimensionality of the tensor (but I assume it is not hard to calculate it for the list of the operations that TF has)
  • type of the operation that will be used to generate the tensor (transpose_1:0, random_uniform:0)
  • type of elements in the tensor (float32)

I have not found this in documentation, but I believe that the values of the variables (and some of the constants are not calculated at the time of assignment).


Take a look at this example:

import tensorflow as tf
from datetime import datetime
dim = 7000

The first example where I just initiate a constant Tensor of random numbers run approximately the same time irrespectibly of dim (0:00:00.003261)

startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
print datetime.now() - startTime

In the second case, where the constant is actually gets evaluated and the values are assigned, the time clearly depends on dim (0:00:01.244642)

startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
sess = tf.Session()
sess.run(m1)
print datetime.now() - startTime

And you can make it more clear by calculating something (d = tf.matrix_determinant(m1), keeping in mind that the time will run in O(dim^2.8))

P.S. I found were it is explained in documentation:

A Tensor object is a symbolic handle to the result of an operation, but does not actually hold the values of the operation’s output.


回答 4

我认为您需要弄清一些基本知识。在上面的示例中,您已经创建了张量(多维数组)。但是要使张量流真正起作用,您必须启动一个“ 会话 ”并在该会话中运行“ 操作 ”。注意单词“会话”和“操作”。您需要了解4件事才能使用tensorflow:

  1. 张量
  2. 运作方式
  3. 届会
  4. 图表

现在,从您写的内容中,您已经给出了张量和操作,但是您没有运行会话或图形。张量(图的边缘)流经图,并由操作(图的节点)操纵。有默认图形,但您可以在会话中启动图形。

说出print时,只能访问定义的变量或常量的形状。

这样您就可以看到丢失的内容:

 with tf.Session() as sess:     
           print(sess.run(product))
           print (product.eval())

希望能帮助到你!

I think you need to get some fundamentals right. With the examples above you have created tensors (multi dimensional array). But for tensor flow to really work you have to initiate a “session” and run your “operation” in the session. Notice the word “session” and “operation”. You need to know 4 things to work with tensorflow:

  1. tensors
  2. Operations
  3. Sessions
  4. Graphs

Now from what you wrote out you have given the tensor, and the operation but you have no session running nor a graph. Tensor (edges of the graph) flow through graphs and are manipulated by operations (nodes of the graph). There is default graph but you can initiate yours in a session.

When you say print , you only access the shape of the variable or constant you defined.

So you can see what you are missing :

 with tf.Session() as sess:     
           print(sess.run(product))
           print (product.eval())

Hope it helps!


回答 5

Tensorflow 1.x

import tensorflow as tf
tf.enable_eager_execution()
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

#print the product
print(product)         # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]

在Tensorflow 2.x中,默认情况下启用了eager模式。因此以下代码适用于TF2.0。

import tensorflow as tf
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

#print the product
print(product)         # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]

In Tensorflow 1.x

import tensorflow as tf
tf.enable_eager_execution()
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

#print the product
print(product)         # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]

With Tensorflow 2.x, eager mode is enabled by default. so the following code works with TF2.0.

import tensorflow as tf
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

#print the product
print(product)         # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]

回答 6

根据上述答案,使用您的特定代码段,您可以像这样打印产品:

import tensorflow as tf
#Initialize the session
sess = tf.InteractiveSession()

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

#print the product
print(product.eval())

#close the session to release resources
sess.close()

Based on the answers above, with your particular code snippet you can print the product like this:

import tensorflow as tf
#Initialize the session
sess = tf.InteractiveSession()

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

#print the product
print(product.eval())

#close the session to release resources
sess.close()

回答 7

在Tensorflow 2.0+中(或在Eager模式环境中),您可以调用.numpy()方法:

import tensorflow as tf

matrix1 = tf.constant([[3., 3.0]])
matrix2 = tf.constant([[2.0],[2.0]])
product = tf.matmul(matrix1, matrix2)

print(product.numpy()) 

In Tensorflow 2.0+ (or in Eager mode environment) you can call .numpy() method:

import tensorflow as tf

matrix1 = tf.constant([[3., 3.0]])
matrix2 = tf.constant([[2.0],[2.0]])
product = tf.matmul(matrix1, matrix2)

print(product.numpy()) 

回答 8

tf.keras.backend.eval 对于评估小表达式很有用。

tf.keras.backend.eval(op)

TF 1.x和TF 2.0兼容。


最小的可验证示例

from tensorflow.keras.backend import eval

m1 = tf.constant([[3., 3.]])
m2 = tf.constant([[2.],[2.]])

eval(tf.matmul(m1, m2))
# array([[12.]], dtype=float32)

这很有用,因为您不必显式创建Sessionor InteractiveSession

tf.keras.backend.eval is useful for evaluating small expressions.

tf.keras.backend.eval(op)

TF 1.x and TF 2.0 compatible.


Minimal Verifiable Example

from tensorflow.keras.backend import eval

m1 = tf.constant([[3., 3.]])
m2 = tf.constant([[2.],[2.]])

eval(tf.matmul(m1, m2))
# array([[12.]], dtype=float32)

This is useful because you do not have to explicitly create a Session or InteractiveSession.


回答 9

您可以通过启用急切执行来检查TensorObject的输出而无需在会话中运行图

只需添加以下两行代码: import tensorflow.contrib.eager as tfe tfe.enable_eager_execution()

在你之后 import tensorflow

输出 print product您的示例中现在为: tf.Tensor([[ 12.]], shape=(1, 1), dtype=float32)

请注意,截至目前(2017年11月),您必须每晚安装Tensorflow构建以启用渴望执行的功能。预制的车轮可以在这里找到。

You can check the output of a TensorObject without running the graph in a session, by enabling eager execution.

Simply add the following two lines of code: import tensorflow.contrib.eager as tfe tfe.enable_eager_execution()

right after you import tensorflow.

The output of print product in your example will now be: tf.Tensor([[ 12.]], shape=(1, 1), dtype=float32)

Note that as of now (November 2017) you’ll have to install a Tensorflow nightly build to enable eager execution. Pre-built wheels can be found here.


回答 10

请注意,这tf.Print()将更改张量名称。如果您要打印的张量是一个占位符,则向其馈送数据将失败,因为在馈送过程中将找不到原始名称。例如:

import tensorflow as tf
tens = tf.placeholder(tf.float32,[None,2],name="placeholder")
print(eval("tens"))
tens = tf.Print(tens,[tens, tf.shape(tens)],summarize=10,message="tens:")
print(eval("tens"))
res = tens + tens
sess = tf.Session()
sess.run(tf.global_variables_initializer())

print(sess.run(res))

输出为:

python test.py
Tensor("placeholder:0", shape=(?, 2), dtype=float32)
Tensor("Print:0", shape=(?, 2), dtype=float32)
Traceback (most recent call last):
[...]
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'placeholder' with dtype float

Please note that tf.Print() will change the tensor name. If the tensor you seek to print is a placeholder, feeding data to it will fail as the original name will not be found during feeding. For example:

import tensorflow as tf
tens = tf.placeholder(tf.float32,[None,2],name="placeholder")
print(eval("tens"))
tens = tf.Print(tens,[tens, tf.shape(tens)],summarize=10,message="tens:")
print(eval("tens"))
res = tens + tens
sess = tf.Session()
sess.run(tf.global_variables_initializer())

print(sess.run(res))

Output is:

python test.py
Tensor("placeholder:0", shape=(?, 2), dtype=float32)
Tensor("Print:0", shape=(?, 2), dtype=float32)
Traceback (most recent call last):
[...]
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'placeholder' with dtype float

回答 11

您应该将TensorFlow Core程序视为由两个独立的部分组成:

  • 建立计算图。
  • 运行计算图。

因此,对于下面的代码,您只需构建计算图。

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

您还需要在TensorFlow程序中初始化所有变量,还必须显式调用一个特殊操作,如下所示:

init = tf.global_variables_initializer()

现在,您要构建图并初始化所有变量,下一步是评估节点,您必须在会话中运行计算图。会话封装了TensorFlow运行时的控件和状态。

以下代码创建一个Session对象,然后调用其run方法来运行足够的计算图以进行评估product

sess = tf.Session()
// run variables initializer
sess.run(init)

print(sess.run([product]))

You should think of TensorFlow Core programs as consisting of two discrete sections:

  • Building the computational graph.
  • Running the computational graph.

So for the code below you just Build the computational graph.

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

You need also To initialize all the variables in a TensorFlow program , you must explicitly call a special operation as follows:

init = tf.global_variables_initializer()

Now you build the graph and initialized all variables ,next step is to evaluate the nodes, you must run the computational graph within a session. A session encapsulates the control and state of the TensorFlow runtime.

The following code creates a Session object and then invokes its run method to run enough of the computational graph to evaluate product :

sess = tf.Session()
// run variables initializer
sess.run(init)

print(sess.run([product]))

回答 12

您可以使用Keras,单行答案将是使用这样的eval方法:

import keras.backend as K
print(K.eval(your_tensor))

You can use Keras, one-line answer will be to use eval method like so:

import keras.backend as K
print(K.eval(your_tensor))

回答 13

试试这个简单的代码!(不言而喻)

import tensorflow as tf
sess = tf.InteractiveSession() # see the answers above :)
x = [[1.,2.,1.],[1.,1.,1.]]    # a 2D matrix as input to softmax
y = tf.nn.softmax(x)           # this is the softmax function
                               # you can have anything you like here
u = y.eval()
print(u)

Try this simple code! (it is self explanatory)

import tensorflow as tf
sess = tf.InteractiveSession() # see the answers above :)
x = [[1.,2.,1.],[1.,1.,1.]]    # a 2D matrix as input to softmax
y = tf.nn.softmax(x)           # this is the softmax function
                               # you can have anything you like here
u = y.eval()
print(u)

回答 14

即使阅读完所有答案,我仍然不容易理解需要执行的操作,直到执行完为止。TensofFlow对我来说也是新的。

def printtest():
x = tf.constant([1.0, 3.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(b))
    sess.close()

但是您仍然可能需要通过执行会话来返回值。

def printtest():
    x = tf.constant([100.0])
    x = tf.Print(x,[x],message="Test")
    init = (tf.global_variables_initializer(), tf.local_variables_initializer())
    b = tf.add(x, x)
    with tf.Session() as sess:
        sess.run(init)
        c = sess.run(b)
        print(c)
        sess.close()

I didn’t find it easy to understand what is required even after reading all the answers until I executed this. TensofFlow is new to me too.

def printtest():
x = tf.constant([1.0, 3.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(b))
    sess.close()

But still you may need the value returned by executing the session.

def printtest():
    x = tf.constant([100.0])
    x = tf.Print(x,[x],message="Test")
    init = (tf.global_variables_initializer(), tf.local_variables_initializer())
    b = tf.add(x, x)
    with tf.Session() as sess:
        sess.run(init)
        c = sess.run(b)
        print(c)
        sess.close()

回答 15

基本上,在tensorflow中,当您创建任何类型的张量时,它们都会创建并存储在其中,只有在运行tensorflow会话时才能访问它们。假设您创建了一个恒定张量,而
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
无需运行会话,则可以获得
op:一个操作。计算该张量的运算。
value_index:int。产生此张量的操作端点的索引。
dtype:DType。存储在该张量中的元素的类型。

要获取值,可以使用所需的张量运行会话:

with tf.Session() as sess:
    print(sess.run(c))
    sess.close()

输出将是这样的:

array([[1。,2.,3.],[4.,5.,6.]],dtype = float32)

Basically, in tensorflow when you create a tensor of any sort they are created and stored inside which can be accessed only when you run a tensorflow session. Say you have created a constant tensor
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Without running a session, you can get
op: An Operation. Operation that computes this tensor.
value_index: An int. Index of the operation’s endpoint that produces this tensor.
dtype: A DType. Type of elements stored in this tensor.

To get the values you can run a session with the tensor you require as:

with tf.Session() as sess:
    print(sess.run(c))
    sess.close()

The output will be something like this:

array([[1., 2., 3.], [4., 5., 6.]], dtype=float32)


回答 16

启用1.10版后在tensorflow中引入的热切执行。它很容易使用。

# Initialize session
import tensorflow as tf
tf.enable_eager_execution()


# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])

print(a)

Enable the eager execution which is introduced in tensorflow after version 1.10. It’s very easy to use.

# Initialize session
import tensorflow as tf
tf.enable_eager_execution()


# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])

print(a)

回答 17

使用https://www.tensorflow.org/api_docs/python/tf/print中提供的提示,我使用该log_d函数来打印格式化的字符串。

import tensorflow as tf

def log_d(fmt, *args):
    op = tf.py_func(func=lambda fmt_, *args_: print(fmt%(*args_,)),
                    inp=[fmt]+[*args], Tout=[])
    return tf.control_dependencies([op])


# actual code starts now...

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

with log_d('MAT1: %s, MAT2: %s', matrix1, matrix2): # this will print the log line
    product = tf.matmul(matrix1, matrix2)

with tf.Session() as sess:
    sess.run(product)

Using tips provided in https://www.tensorflow.org/api_docs/python/tf/print I use the log_d function to print formatted strings.

import tensorflow as tf

def log_d(fmt, *args):
    op = tf.py_func(func=lambda fmt_, *args_: print(fmt%(*args_,)),
                    inp=[fmt]+[*args], Tout=[])
    return tf.control_dependencies([op])


# actual code starts now...

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

with log_d('MAT1: %s, MAT2: %s', matrix1, matrix2): # this will print the log line
    product = tf.matmul(matrix1, matrix2)

with tf.Session() as sess:
    sess.run(product)

回答 18

import tensorflow as tf
sess = tf.InteractiveSession()
x = [[1.,2.,1.],[1.,1.,1.]]    
y = tf.nn.softmax(x)           

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

print(product.eval())
tf.reset_default_graph()
sess.close()
import tensorflow as tf
sess = tf.InteractiveSession()
x = [[1.,2.,1.],[1.,1.,1.]]    
y = tf.nn.softmax(x)           

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)

print(product.eval())
tf.reset_default_graph()
sess.close()

回答 19

现在不建议使用tf.Print,这是使用tf.print(小写p)的方法。

虽然运行会话是一个不错的选择,但并非总是可行的。例如,您可能想在特定会话中打印一些张量。

新的打印方法返回一个没有输出张量的打印操作:

print_op = tf.print(tensor_to_print)

由于它没有输出,因此无法像使用tf.Print一样将其插入到图形中。相反,您可以添加它以控制会话中的依赖项,以便使其打印。

sess = tf.compat.v1.Session()
with sess.as_default():
  tensor_to_print = tf.range(10)
  print_op = tf.print(tensor_to_print)
with tf.control_dependencies([print_op]):
  tripled_tensor = tensor_to_print * 3
sess.run(tripled_tensor)

有时,在较大的图中(可能部分由子函数创建),将print_op传播到会话调用很麻烦。然后,可以使用tf.tuple将打印操作与另一个操作耦合,然后无论哪个会话执行代码,该操作都将与该操作一起运行。这是完成的方式:

print_op = tf.print(tensor_to_print)
some_tensor_list = tf.tuple([some_tensor], control_inputs=[print_op])
# Use some_tensor_list[0] instead of any_tensor below.

tf.Print is now deprecated, here’s how to use tf.print (lowercase p) instead.

While running a session is a good option, it is not always the way to go. For instance, you may want to print some tensor in a particular session.

The new print method returns a print operation which has no output tensors:

print_op = tf.print(tensor_to_print)

Since it has no outputs, you can’t insert it in a graph the same way as you could with tf.Print. Instead, you can you can add it to control dependencies in your session in order to make it print.

sess = tf.compat.v1.Session()
with sess.as_default():
  tensor_to_print = tf.range(10)
  print_op = tf.print(tensor_to_print)
with tf.control_dependencies([print_op]):
  tripled_tensor = tensor_to_print * 3
sess.run(tripled_tensor)

Sometimes, in a larger graph, maybe created partly in subfunctions, it is cumbersome to propagate the print_op to the session call. Then, tf.tuple can be used to couple the print operation with another operation, which will then run with that operation whichever session executes the code. Here’s how that is done:

print_op = tf.print(tensor_to_print)
some_tensor_list = tf.tuple([some_tensor], control_inputs=[print_op])
# Use some_tensor_list[0] instead of any_tensor below.

回答 20

问题:如何在TensorFlow中打印Tensor对象的值?

回答:

import tensorflow as tf

# Variable
x = tf.Variable([[1,2,3]])

# initialize
init = (tf.global_variables_initializer(), tf.local_variables_initializer())

# Create a session
sess = tf.Session()

# run the session
sess.run(init)

# print the value
sess.run(x)

Question: How to print the value of a Tensor object in TensorFlow?

Answer:

import tensorflow as tf

# Variable
x = tf.Variable([[1,2,3]])

# initialize
init = (tf.global_variables_initializer(), tf.local_variables_initializer())

# Create a session
sess = tf.Session()

# run the session
sess.run(init)

# print the value
sess.run(x)