MLEnthusiast
MLEnthusiast

Reputation: 223

How to get Numpy array from tf Tensor?

I face problems when trying to get a numpy array from a tensorflow tensor. I use a tensorflow hub module but I don't want to use tensorflow in downstream tasks but rather need a numpy array.

I know that I have to call the 'eval()' method on the tensor from within a tensorflow session. But unfortuantely I cannot get it to work... :( It tells me that the "tables are not initialized". I tried to add 'sess.run(tf.tables_initializer())' but then I get the error: 'NotFoundError: Resource localhost/module_1/embeddings_morph_specialized/class tensorflow::Var does not exist'. I am not sure what to try next. I have also tried 'sess.run()' but have also been unsuccessful.

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub

embed = hub.Module("https://public.ukp.informatik.tu-darmstadt.de/arxiv2018-xling-sentence-embeddings/tf-hub/monolingual/1")
X = embed(["This is a test."])

# I tried:
#with tf.Session() as sess:
#    sess.run(tf.tables_initializer())
#    X.eval()

'X' is the tensor which I would like to convert to a numpy array.

Any help is appreciated. :) Thank you.

Upvotes: 1

Views: 718

Answers (1)

Stewart_R
Stewart_R

Reputation: 14485

Unfortunately, tf_hub modules are not yet supported in eager mode except in tf 2 (which is still in beta and I think needs slightly different hub modules anyway).

Therefore you'll need to run this in a session.

Something like:

embed = hub.Module("https://public.ukp.informatik.tu-darmstadt.de/arxiv2018-xling-sentence-embeddings/tf-hub/monolingual/1")
X = embed(["This is a test."])

with tf.Session() as session:
  session.run([tf.global_variables_initializer(), tf.tables_initializer()])
  numpy_arr = session.run(X)

Upvotes: 1

Related Questions