Converting PyObject to a Julia array

How to convert PyObject into a Julia array

import PyCall
tf = PyCall.pyimport("tensorflow")
o = tf[:random_normal]((3,3))
PyObject <tf.Tensor: id=27, shape=(3, 3), dtype=float32, numpy=
array([[0.02705349, 0.3173014 , 0.48765275],
       [0.03795605, 0.7796892 , 0.01696282],
       [0.9305789 , 0.3821437 , 0.26405492]], dtype=float32)>

Friendly nudge: PSA: how to quote code with backticks

2 Likes

Convert it to a numpy array python - Convert a tensor to numpy array in Tensorflow? - Stack Overflow

PyCall then automatically converts it to a Julia’s Array (provided that element type can be converted).

1 Like

it does not seem to work:

import PyCall
tf = PyCall.pyimport("tensorflow")
o = tf[:random_normal]((3,3))[:eval]
PyObject <tf.Tensor: id=27, shape=(3, 3), dtype=float32, numpy=
array([[0.02705349, 0.3173014 , 0.48765275],
       [0.03795605, 0.7796892 , 0.01696282],
       [0.9305789 , 0.3821437 , 0.26405492]], dtype=float32)>

Don’t you need to execute the eval function as well?

actually this is what works:

o = tf[:random_normal]((3,3))[:numpy]()
3×3 Array{Float32,2}:
 -1.35462   -0.0406312  -0.993727
 -0.8862     1.15086    -1.85081
  0.461948  -1.41717    -0.993305

Thank you very much!

I found the answer from the issue on the TensorFlow-Examples.
https://github.com/aymericdamien/TensorFlow-Examples/issues/40#issuecomment-405892316

so using PyCall in that way.

using PyCall
tf = pyimport("tensorflow")
o = tf[:random_normal]((3,3))
@pyimport tensorflow.python.keras.backend as K
sess = K.get_session()
array = sess[:run](o)

and by adding Base.getproperty to PyObject.

Base.getproperty(o::PyObject, name::Symbol) = (:o == name ? getfield : getindex)(o, name)

array = sess.run(o)

now it gets more python-like code.