3

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?

1

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.