简体   繁体   中英

How can I convert a tensor into a ndarray in TensorFlow?

My goal is to convert a tensor into a ndarray without 'run' or 'eval'. I wanted to perform the same operation as the example.

A = tf.constant(5)
B = tf.constant([[A, 1], [0,0]])

However, ndarray can be inside tf.constant but tensor cannot. Therefore, I tried to perform the operation using the following example, but tf.make_ndarray does not work.

A = tf.constant(5)
C = tf.make_ndarray(A)
B = tf.constant([[C, 1], [0,0]])

https://github.com/tensorflow/tensorflow/issues/28840#issuecomment-509551333

As mentioned in the github link above, tf.make_ndarray does not work. To be precise, an error occurs because tensorflow requires a 'tensor_shape' that does not exist, instead of a 'shape' that exists.

How can I run the code in this situation?

tf.make_ndarray is used to convert TensorProto values into NumPy arrays. These values are generally the constants used in a graph. For example, when you use tf.constant , you create a Const operation with an attribute value holding the constant value that the operation will produce. That attribute is stored as a TensorProto . Hence, you can "extract" the value of a Const operation as a NumPy array like this:

import tensorflow as tf

A = tf.constant(5)
C = tf.make_ndarray(A.op.get_attr('value'))
print(C, type(C))
# 5 <class 'numpy.ndarray'>

In general, though, you cannot convert arbitrary tensors into NumPy arrays, as their values will depend on the values of the variables and the fed inputs within a particular session.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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