Factorized_top_k using tensorflow recommenders

I followed the tensorflow recommenders movie ranking tutorial and built the model. Now I would like to get top_k recommendations using the model. This is what I tried:

layer = tfrs.layers.factorized_top_k.Streaming(model.ranking_model)
layer.index(movies.map(model.ranking_model.movie_embeddings), movies)
tracks = layer.query_with_exclusions(
    queries=np.array([["42", "52"]]),
    exclusions= np.array([[]])
) 

But it throws the error “iterating over tf.Tensor is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.”

How to invoke the query_with_exclusions() function correctly?

3 Likes

Also interested in the answer to this, and how one could use this function to remove all previously interacted with items for each user.

1 Like

I’m trying to use query_with_exclusions too. Would love some insights

Try this:

layer = tfrs.layers.factorized_top_k.Streaming(model.ranking_model)

layer.index_from_dataset(

    tf.data.Dataset.zip((movies.batch(100), movies.batch(100).map(model.movie_model)))

)

tracks = layer.query_with_exclusions(

    queries=np.array([['movie_title']]),

    exclusions= np.array([["42"]]) # movie you want to exclude

)

I find the first line of code confusing. The documentation for tfrs.layers.factorized_top_k.Streaming says it takes a query model, yet the code here passes a ranking model. A query model typically accepts as input information about a user, while a ranking model typically accepts as input information about a user and item (and possibly additional context about the interaction).

So it seems the first line should instead be:

layer = tfrs.layers.factorized_top_k.Streaming(model.ranking_model.user_embeddings)