Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16418

How to get a value from a tf.tensor that has the data type string?

$
0
0

I am following the Tensorflow Recommenders tutorial (Tensorflow Recommenders). I managed to build a working model with multiple features for the query and candidate model.

However, it gets tricky when trying to obtain predictions. The tutorial only provides an example for the very basic case of using only movie titles and user ids. I am trying to obtain recommendations for an entire dataset based upon multiple features.

# Use brute-force search to set up retrieval using the trained representationsindex = tfrs.layers.factorized_top_k.BruteForce(model.query_model, k=2)index.index_from_dataset(    test_interactions.batch(100).map(lambda features: (        features['movie_title'],        model.candidate_model({"movie_title": features['movie_title'],'category': features['category'],        })    )))# Get some recommendationsrec = test_interactions.batch(100).map(lambda features:     index({"user_id": features["user_id"],"timestamp": features["timestamp"],    }))# Evaluate the recommendationsfor _, recommendations in rec:    movie_ids = [tensor.numpy() for tensor in recommendations]    print(f"Recommendations: {movie_ids}")This only returns the following:Recommendations: [array([b'Tensor("args_1:0", shape=(), dtype=string)',       b'Tensor("args_1:0", shape=(), dtype=string)'], dtype=object), array([b'Tensor("args_1:0", shape=(), dtype=string)',       b'Tensor("args_1:0", shape=(), dtype=string)'], dtype=object), array([b'Tensor("args_1:0", shape=(), dtype=string)',       b'Tensor("args_1:0", shape=(), dtype=string)'], dtype=object), array([b'Tensor("args_1:0", shape=(), dtype=string)',       b'Tensor("args_1:0", shape=(), dtype=string)'], dtype=object), array([b'Tensor("args_1:0", shape=(), dtype=string)', ......

I have already found out it has something to do with how Tensorflow datasets handle strings and I should be using tf.py_function. However, I have tried building a function, yet it doesnt allow for dictionaries. So I only tried converting solely the customer_id, which did change nothing about the output.

My attempt looked the following:

tf.py_function(Tout=tf.string)def get_data(row):    return row.numpy()for i in test_interactions:    print(get_data(i['user_id']))

Which outputs:

b'Tensor("args_2:0", shape=(), dtype=string)'

I really do not understand how I can just get the movie_titles instead of this tensor representation… Ideally I would also want the customer_id : [‘movie_title_1’, ‘movie_title_2’].


Viewing all articles
Browse latest Browse all 16418

Trending Articles