如何在TensorFlow中将张量转换为numpy数组? [英] How can I convert a tensor into a numpy array in TensorFlow?

查看:104
本文介绍了如何在TensorFlow中将张量转换为numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

Session.runeval返回的任何张量都是NumPy数组.

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'>

或者:

>>> 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.runeval()返回的任何张量不是NumPy数组.例如,稀疏张量返回为SparseTensorValue:

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'>

这篇关于如何在TensorFlow中将张量转换为numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆