Converting PyObject to a Julia array


#1

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


#2

Friendly nudge: PSA: how to quote code with backticks


#3

Convert it to a numpy array https://stackoverflow.com/questions/34097281/how-can-i-convert-a-tensor-into-a-numpy-array-in-tensorflow

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


#4

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

#5

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


#6

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!


#7

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.