# tfrs.layers.factorized_top_k.ScaNN

<br />

|---|
| [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png) View source on GitHub](https://github.com/tensorflow/recommenders/blob/v0.7.7/tensorflow_recommenders/layers/factorized_top_k.py#L613-L796) |

ScaNN approximate retrieval index for a factorized retrieval model.

Inherits From: [`TopK`](https://www.tensorflow.org/recommenders/api_docs/python/tfrs/layers/factorized_top_k/TopK)

    tfrs.layers.factorized_top_k.ScaNN(
        query_model: Optional[tf.keras.Model] = None,
        k: int = 10,
        distance_measure: Text = 'dot_product',
        num_leaves: int = 100,
        num_leaves_to_search: int = 10,
        training_iterations: int = 12,
        dimensions_per_block: int = 2,
        num_reordering_candidates: Optional[int] = None,
        parallelize_batch_searches: bool = True,
        name: Optional[Text] = None
    )

### Used in the notebooks

| Used in the tutorials |
|---|
| - [Efficient serving](https://www.tensorflow.org/recommenders/examples/efficient_serving) - [Recommending movies: retrieval](https://www.tensorflow.org/recommenders/examples/basic_retrieval) |

This layer uses the state-of-the-art
[ScaNN](https://github.com/google-research/google-research/tree/master/scann)
library to retrieve the best candidates for a given query.

To understand how to use this layer effectively, have a look at the efficient
retrieval
[tutorial](https://www.tensorflow.org/recommenders/examples/efficient_serving).

To deploy this layer in TensorFlow Serving you can use our customized
TensorFlow Serving Docker container, available on
[Docker Hub](https://hub.docker.com/r/google/tf-serving-scann). You can also
build the image yourself from the
[Dockerfile](https://github.com/google-research/google-research/tree/master/scann/tf_serving).

<br />

<br />

<br />

| ## Args ||
|---|---|
| `query_model` | Optional Keras model for representing queries. If provided, will be used to transform raw features into query embeddings when querying the layer. If not provided, the layer will expect to be given query embeddings as inputs. |
| `k` | Default number of results to retrieve. Can be overridden in `call`. |
| `distance_measure` | Distance metric to use. |
| `num_leaves` | Number of leaves. |
| `num_leaves_to_search` | Number of leaves to search. |
| `training_iterations` | Number of training iterations when performing tree building. |
| `dimensions_per_block` | Controls the dataset compression ratio. A higher number results in greater compression, leading to faster scoring but less accuracy and more memory usage. |
| `num_reordering_candidates` | If set, the index will perform a final refinement pass on `num_reordering_candidates` candidates after retrieving an initial set of neighbours. This helps improve accuracy, but requires the original representations to be kept, and so will increase the final model size." |
| `parallelize_batch_searches` | Whether batch querying should be done in parallel. |
| `name` | Name of the layer. |

<br />

<br />

<br />

<br />

| ## Raises ||
|---|---|
| `ImportError` | if the scann library is not installed. |

<br />

## Methods

### `call`

[View source](https://github.com/tensorflow/recommenders/blob/v0.7.7/tensorflow_recommenders/layers/factorized_top_k.py#L750-L793)

    call(
        queries: Union[tf.Tensor, Dict[Text, tf.Tensor]], k: Optional[int] = None
    ) -> Tuple[tf.Tensor, tf.Tensor]

Query the index.

<br />

<br />

<br />

| Args ||
|---|---|
| `queries` | Query features. If `query_model` was provided in the constructor, these can be raw query features that will be processed by the query model before performing retrieval. If `query_model` was not provided, these should be pre-computed query embeddings. |
| `k` | The number of candidates to retrieve. If not supplied, defaults to the `k` value supplied in the constructor. |

<br />

<br />

<br />

<br />

| Returns ||
|---|---|
| Tuple of (top candidate scores, top candidate identifiers). ||

<br />

<br />

<br />

<br />

| Raises ||
|---|---|
| ValueError if `index` has not been called. ||

<br />

### `index`

[View source](https://github.com/tensorflow/recommenders/blob/v0.7.7/tensorflow_recommenders/layers/factorized_top_k.py#L712-L748)

    index(
        candidates: tf.Tensor, identifiers: Optional[tf.Tensor] = None
    ) -> 'ScaNN'

Builds the retrieval index.

When called multiple times the existing index will be dropped and a new one
created.

<br />

<br />

<br />

| Args ||
|---|---|
| `candidates` | Matrix of candidate embeddings. |
| `identifiers` | Optional tensor of candidate identifiers. If given, these will be used as identifiers of top candidates returned when performing searches. If not given, indices into the candidates tensor will be returned instead. |

<br />

<br />

<br />

<br />

| Returns ||
|---|---|
| Self. ||

<br />

### `index_from_dataset`

[View source](https://github.com/tensorflow/recommenders/blob/v0.7.7/tensorflow_recommenders/layers/factorized_top_k.py#L179-L215)

    index_from_dataset(
        candidates: tf.data.Dataset
    ) -> 'TopK'

Builds the retrieval index.

When called multiple times the existing index will be dropped and a new one
created.

<br />

<br />

<br />

| Args ||
|---|---|
| `candidates` | Dataset of candidate embeddings or (candidate identifier, candidate embedding) pairs. If the dataset returns tuples, the identifiers will be used as identifiers of top candidates returned when performing searches. If not given, indices into the candidates dataset will be given instead. |

<br />

<br />

<br />

<br />

| Returns ||
|---|---|
| Self. ||

<br />

<br />

<br />

<br />

| Raises ||
|---|---|
| ValueError if the dataset does not have the correct structure. ||

<br />

### `is_exact`

[View source](https://github.com/tensorflow/recommenders/blob/v0.7.7/tensorflow_recommenders/layers/factorized_top_k.py#L795-L796)

    is_exact() -> bool

Indicates whether the results returned by the layer are exact.

Some layers may return approximate scores: for example, the ScaNN layer
may return approximate results.

<br />

<br />

<br />

| Returns ||
|---|---|
| True if the layer returns exact results, and False otherwise. ||

<br />

### `query_with_exclusions`

[View source](https://github.com/tensorflow/recommenders/blob/v0.7.7/tensorflow_recommenders/layers/factorized_top_k.py#L242-L288)

    @tf.function
    query_with_exclusions(
        queries: Union[tf.Tensor, Dict[Text, tf.Tensor]],
        exclusions: tf.Tensor,
        k: Optional[int] = None
    ) -> Tuple[tf.Tensor, tf.Tensor]

Query the index.

<br />

<br />

<br />

| Args ||
|---|---|
| `queries` | Query features. If `query_model` was provided in the constructor, these can be raw query features that will be processed by the query model before performing retrieval. If `query_model` was not provided, these should be pre-computed query embeddings. |
| `exclusions` | `[query_batch_size, num_to_exclude]` tensor of identifiers to be excluded from the top-k calculation. This is most commonly used to exclude previously seen candidates from retrieval. For example, if a user has already seen items with ids "42" and "43", you could set exclude to `[["42", "43"]]`. |
| `k` | The number of candidates to retrieve. Defaults to constructor `k` parameter if not supplied. |

<br />

<br />

<br />

<br />

| Returns ||
|---|---|
| Tuple of (top candidate scores, top candidate identifiers). ||

<br />

<br />

<br />

<br />

| Raises ||
|---|---|
| ValueError if `index` has not been called. ValueError if `queries` is not a tensor (after being passed through the query model). ||

<br />