Zero Labs
Industry News / AI

Build an Art Recommender from scratch with CLIP and ChromaDB

Source · Towards AI By Simon Calò

From the publisher’s feed, collected in the ZeroLabs newsroom.

Part II: The vector database and its functionsRocks at Port-Goulphar, Belle Île by Claude Monet, retrieved from the API of the Art Institute of Chicago (ARTIC).In the last part of this tutorial, we collected high-quality art data. It is now time to design a database with useful functionalities so that we can store, organise, and interact with our data programmatically. At this stage, it’s valuable to take some time to think about what functionalities will be needed for our recommender down the line. That way, we can make sure to include those capabilities while setting up the database. In practice, this would be an iterative process, as more features will become desirable once we start testing our app. But let’s not get ahead of ourselves, and start from why we’re doing this in the first place.As a note, I am not going to dive into embedding spaces, vector similarity, distance measures, etc. These are central concepts to fully understand what we are going to do in this tutorial. Although they are not necessary to follow the tutorial, I’d recommend taking some time to read up on these topics. Some useful references will be included through the article.Why we should embed our dataOn a surface level, this question turns out not to be too interesting. We need to embed our data to have structures ML models can work with. But there are several methods to embed images. So, the relevant questions actually are how we intend to embed our data, and why we choose that specific strategy. We could do it based on the metadata of the image: its author, the year in which it was made, the colours, and so on. It could also be an intensity value for each pixel of the image. The choice of the embedding strategy also informs the kind of database we should use. If we were to choose the metadata-driven approach, for instance, we could rely on a SQL database, which is easy to query and widely adopted.To answer these critical questions, we need to remind ourselves what we intend to do with our images. And that is to build a recommender. It turns out that what fuels a basic recommender system comes down to the concept of similarity. And, specifically, semantic similarity. If you love naturalistic artworks, I cannot simply recommend you paintings by Monet that contain the colour green. If two paintings are from wildly different eras, regions and artists, they might still be relevant to recommend if they both represent a forest at dawn. We need to have a method to understand the semantics of those artworks, and realise that a common theme there is nature. Encoding this kind of information in a vector is no trivial task. Lucky for us, AI labs have been tackling this problem already and released their results as open-source models.Ok, now we are clear on our requirements: we want to embed our images based on their semantics, and we want to store the embeddings in a database that allows us to perform vector operations, especially similarity-driven retrieval. Let me show you how you can achieve that by relying on CLIP and ChromaDB.CLIP: Our multi-modal embedderCLIP is a well-known foundation model developed by OpenAI. It is multi-modal, meaning that it can encode both images and text onto the same vector space. And that is really where its strength and beauty lies. The basic intuition behind it is simple: train a model that maps images and their description to the same vector. At the same time, ensure that different images and different descriptions are mapped to different vectors. And because of this simple intuition, the core of the mathematics boils down to matrix diagonalisation. Simple enough, no? Learning about this model was truly eye-opening for me. In order to stick to the topic, I won’t go into details, but here are some good references: a clear and comprehensive Medium article, the original blog post from OpenAI, and, if you want to dive into the technical details, the scientific paper.Figure taken from Radford, A., Kim, J. W., Hallacy, C., Ramesh, A., Goh, G., Agarwal, S., … & Sutskever, I. (2021, July). Learning transferable visual models from natural language supervision. In International conference on machine learning (pp. 8748–8763). PmLR. It exemplifies the training process of CLIP where images and their captions are mapped to the same vector space.Building our database with ChromaDBOk, we now know what strategy we want to use to encode our data, so it’s time to get building. We are going to do this with the help of ChromaDB. ChromaDB is an open-source, easy to use library to build vector databases. It is designed for intuitive vector storage and retrieval, and with multi-modal capabilities in mind. It suits our use case perfectly. I built a wrapper class around the ChromaDB API to add some functionalities and customise it to our specific use case (my code might be a bit old now, so I encourage you to check out the latest features from ChromaDB). Let’s look at the code.from typing import Optionalimport chromadbfrom chromadb.utils import embedding_functionsfrom chromadb.utils.data_loaders import ImageLoaderimport osimport jsonfrom embeddings_creation.config.chroma_db_generator_config import ( CHROMA_DATA_PATH, vector_similarity,)import numpy as npfrom embeddings_creation.src.data_models import EmbeddingDatafrom helper_functions.vector_helpers import compute_cosine_similaritiesclass ChromaDBGenerator: """Class to create and interact with ChromaDB SQL database. This class allows to store image in vector format and retrieve them using text or vector queries. """ def __init__( self, collection_name: str, images_path: str, jsons_path: str, similarity_measure: str = "cosine_similarity", include_data_loader: bool = True, ) -> None: """Instantiate an object of the class. Args: collection_name: Name for the ChromaDB collection of images. images_path: Path where the images to be stored in the collection are. jsons_path: Path where the jsons to be stored as metadata in the collection are. similarity_measure: The method to determine vector similarity. Defaults to "cosine_similarity". include_data_loader: Whether to specify data loader object. Needed for images. Defaults to True. """ self.CHROMA_DATA_PATH = CHROMA_DATA_PATH self.COLLECTION_NAME = collection_name self.images_path = images_path self.jsons_path = jsons_path self.similarity_measure = similarity_measure self.client = chromadb.PersistentClient(path=self.CHROMA_DATA_PATH) # currently, this is the only available model for images within ChromaDB # alternatively, it's possible to use other methods to generate embeddings and # simply store the embeddings in ChromaDB self.embedding_func = embedding_functions.OpenCLIPEmbeddingFunction() # only include data_loader if specified self.image_loader = ImageLoader() if include_data_loader else None # create the collection or get it if it already exists self.collection = self.client.get_or_create_collection( name=self.COLLECTION_NAME, embedding_function=self.embedding_func, data_loader=self.image_loader, metadata=vector_similarity[self.similarity_measure], ) self.image_names = [] self.jsons = []This is how I’ve configured the __init__ method of the class that is controlling the interactions with our vector database. First of all, we need to tell ChromaDB where to store its data in vector format, via CHROMA_DATA_PATH (when creating an instance of this class you will see folders appear at this path); then we need to pick a name for our data collection (this can be whatever you like). It’s important to stay consistent, since you can handle multiple collections via the same instance. Other important aspects are:similarity_measure, which we use to control how the similarity between vectors should be defined. I have used cosine similarity as the default.The persistent client which is our connection to communicate with the underlying DB. Persistent here means that Chroma will store the data locally on disk so when we start a new session, our data will still be available, and we won’t need to embed it again.The embedding function we are using. You can see that we are specifying that we want to use CLIP (defined via chromadb.utils.embedding_functions.OpenCLIPEmbeddingFunction()).A pre-defined image loader function (chromadb.utils.data_loaders.ImageLoader()), to handle and pre-process images consistently before embedding them.After having defined these parameters, we can create our ChromaDB collection, which will contain data all pre-processed in the same way, embedded with the same function, and which will be retrieved using the same strategies.Before moving forward, it’s worth taking a look at how the configurations for our data collection have been defined:vector_similarity = { "cosine_similarity": {"hnsw:space": "cosine"}, "l2_norm": {"hnsw:space": "l2"}, "inner_product": {"hnsw:space": "ip"},}Via this simple dictionary, we can specify to ChromaDB which similarity functions we want to have available. In case you want to try methods other than cosine similarity, a few alternatives are defined above. I won’t go into details, but if you’re curious, it’s worth understanding what hnsw stands for. It is a concept at the core of effective retrieval. Here is a good source.What functionalities should our database have?Now let’s think about what we want our database to do. First, it should transform our images into vectors.def retrieve_images_and_jsons(self) -> None: """Retrieve all the image names and jsons in the provided paths.""" # get all files ending with .jpg self.image_names = [f for f in os.listdir(self.images_path) if f.endswith(".jpg")] # for each image, collect the relative metadata for image_name in self.image_names: json_name = image_name.rstrip(".jpg") + ".json" with open(f"{self.jsons_path}/{json_name}", "r") as file: json_data = json.load(file) # remove all items that don't conform to the ChromaDB requirements json_data = { k: v for k, v in json_data.items() if isinstance(v, (str, int, float, bool)) } self.jsons.append(json_data) def add_image_data_to_collection(self, add_metadata: bool = False) -> None: """Add images data to collection. if add_metadata = True, then add the metadata contained in the jsons as well. Adding metadata might result in problems due to a non-standardised format of the json files. Args: add_metadata: Whether to add metadata for each image in the collection. Defaults to False. """ self.retrieve_images_and_jsons() # NOTE: metadata can only be added if the jsons do not contain None values metadatas = self.jsons if add_metadata else None self.collection.add( ids=[image_name.rstrip(".jpg") for image_name in self.image_names], uris=[f"{self.images_path}/{image_name}" for image_name in self.image_names], metadatas=metadatas, )def add_text_data_to_collection(self, ids: list[str], documents: list[str]) -> None: """Add text data to the collection. Args: ids: A list of all the ids for the documents. documents: The text documents to be added to the collection. """ self.collection.add( ids=ids, documents=documents, )The three functions above are used to:get all the image names and jsons we have downloaded in the previous chapteradd images to our collection in the form of vectorsand include the possibility of adding text data to our collection.Remember that this last feature is made possible by the fact that CLIP is a multi-modal embedder. And yes, it is literally this simple to convert all our artworks into vectors ready to be queried. Notice that adding the metadata to the images is optional. This is because if the metadata contains None values, you might run into some problems. If you have clean metadata, then add it; it will allow you to make your retrieval much more nuanced.The next feature is being able to retrieve the embeddings corresponding to selected images. Not only because it will be useful down the line for similarity, but also because it allows us to peek under the hood and see how our images are being turned into vectors. We can see which kind of structure these vectors have and we can compare whether two images that look similar also have similar embeddings.def retrieve_embeddings_of_images(self, images_ids: list[str]) -> list[float]: """Retrieve a list of the embeddings of all the chosen images. In case an id is incorrect, the method returns no embedding for it, but does not throw an exception. Args: images_ids: A list of all the image_ids for which we want to retrieve the vector embeddings. Returns: A list of the vector embeddings of the chosen images. """ # In case the list is empty, return an empty list back if not images_ids: return [] # Note: if you pass an empty list, this method still returns embeddings vector_embeddings = self.collection.get( ids=images_ids, include=["embeddings"], )["embeddings"] return vector_embeddingsAgain, extremely simple. I hope you are starting to see why we picked ChromaDB.Now, let’s start going into more complex territory. The first function we can look at is how to retrieve images based on a text query. Yes, you can write any kind of natural language query and observe what the images most similar to it are.def find_n_most_similar_to_text( self, query_text: str, n: int = 10, metadata_filters: dict = None, params_to_output: Optional[list[str]] = None,) -> list[EmbeddingData]: """Retrieve the n most fitting artworks to a given text query. Args: query_text: The text query. n: The number of matching results to find. Defaults to 10. metadata_filters: A dictionary containing metadata filters. For more details on how to use this argument, visit: https://docs.trychroma.com/usage-guide Defaults to None. params_to_output: A list containing the parameters to output from the query. Defaults to ["distances", "uris", "embeddings"]. Returns: A list of EmbeddingData objects containing the matching results. """ if params_to_output is None: params_to_output = ["distances", "uris", "embeddings"] if n return [] # if more output parameters are needed, modify the include argument results = self.collection.query( query_texts=[query_text], n_results=n, where=metadata_filters, include=params_to_output, ) return [ EmbeddingData( id=results["ids"][0][i], distance=results["distances"][0][i], image_path=results["uris"][0][i], embedding=results["embeddings"][0][i] ) for i in range(len(results["ids"][0])) ]Still simple enough. Essentially we just call the query method from the ChromaDB API, and structure the result with our own format. You can pass the number of results you want to retrieve, any metadata filters you might have in mind (such as author or specific eras), and which parameters you want your results to contain. For now we will stick to distances from the vector corresponding to our query, the uris (aka the paths to the images) and the embeddings of those images. To standardise how our results from this kind of queries will be, I have introduced a data class here. It allows us to be consistent in terms of inputs and outputs for different functions within (and also outside of) this class.For most of our use cases, we will want to retrieve images similar to a given image or vector. To enable this, it makes sense to include some extra functionalities.def find_n_most_similar_to_vector( self, vector: list[float], n: int = 10, params_to_output: Optional[list[str]] = None, metadata_filters: Optional[dict] = None, image_ids_to_be_distant_from: Optional[list[str]] = None, similarity_threshold: float = 0.9, factor_for_extra_retrieval: int = 5, similarity_threshold_step: float = 0.05, factor_increase_step: int = 1, ) -> list[EmbeddingData]: """Retrieve the n most similar artworks to a given embedding vector. Args: vector: The embedding vector to find similar artworks to. n: The number of matching results to find. Defaults to 10. metadata_filters: A dictionary containing metadata filters. For more details on how to use this argument, visit: https://docs.trychroma.com/usage-guide Defaults to None. params_to_output: A list containing the parameters to output from the query. Defaults to ["distances", "uris", "embeddings"]. image_ids_to_be_distant_from: Image IDs that we want the output images to be different from. similarity_threshold: A threshold for excluding results considered too similar to the provided image IDs to be distant from. Defaults to 0.9. factor_for_extra_retrieval: Factor to increase query size to compensate for potential filtering. Defaults to 5. similarity_threshold_step: How much to decrease the similarity threshold in each consecutive recursive call. Defaults to 0.05. factor_increase_step: How much to increase the retrieval factor in each recursive call. Defaults to 1. Returns: A list of EmbeddingData objects containing the matching results. """ if params_to_output is None: params_to_output = ["distances", "uris", "embeddings"] if n return [] query_size = (n * factor_for_extra_retrieval) if image_ids_to_be_distant_from else n # if more output parameters are needed, modify the include argument results = self.collection.query( query_embeddings=[vector], n_results=query_size, where=metadata_filters, include=params_to_output, ) if image_ids_to_be_distant_from is None: return [ EmbeddingData( id=results["ids"][0][i], distance=results["distances"][0][i], image_path=results["uris"][0][i], embedding=results["embeddings"][0][i] ) for i in range(len(results["ids"][0])) ] embeddings_to_be_distant_from = self.collection.get( ids=image_ids_to_be_distant_from, include=["embeddings"] )["embeddings"] images_similarities = compute_cosine_similarities( vectors1=np.array(results["embeddings"][0]), vectors2=np.array(embeddings_to_be_distant_from) ) # mark all the images to be removed remove_mask = np.any(images_similarities > similarity_threshold, axis=1) result_to_output = [ EmbeddingData( id=results["ids"][0][i], distance=results["distances"][0][i], image_path=results["uris"][0][i], embedding=results["embeddings"][0][i] ) for i in range(len(results["ids"][0])) if not remove_mask[i] ] if len(result_to_output) >= n: return result_to_output[:n] # if we were not able to retrieve enough images # call the function recursively with a lower similarity threshold # and a higher factor to extract more images return self.find_n_most_similar_to_vector( vector=vector, n=n, metadata_filters=metadata_filters, params_to_output=params_to_output, image_ids_to_be_distant_from=image_ids_to_be_distant_from, similarity_threshold=similarity_threshold-similarity_threshold_step, factor_for_extra_retrieval=factor_for_extra_retrieval+factor_increase_step, similarity_threshold_step=similarity_threshold_step, factor_increase_step=factor_increase_step, )The core of the function is simple enough, which is just to again use the query method with thequery_embedding argument. But you are probably wondering why I’ve added so many extra functionalities. Why would we care about avoiding being too close to certain images? That aspect alone is forcing us to add so much extra logic. The answer is that this will come in handy when we build the actual recommender. Say, for instance, that one of our users disliked a few images already while interacting with our app. Don’t you think they would get frustrated if upon providing them with new recommendations, we included an image similar to one they explicitly disliked? It might compromise user engagement and that’s why I’ve decided to include this extra logic, which ensures we stay away from disliked images. This added feature forces us to include a recursive step in our function to adjust the definition of “distant enough”, relaxing the requirement in successive calls, in case we aren’t able to find images satisfying our constraints. If you don’t find this functionality useful, feel free to remove it. It’s very easy to do so; just follow the logic when image_ids_to_be_distant_from = None .Now that we have this function, we can query the images most similar to a given image.def find_n_most_similar_to_image( self, image_id: str, n: int = 10, metadata_filters: dict = None, params_to_output: Optional[list[str]] = None,) -> list[EmbeddingData]: """Retrieve the n most similar artworks to a given artwork. Args: image_id: The id of the image to find similar images to. n: The number of matching results to find. Defaults to 10. metadata_filters: A dictionary containing metadata filters. For more details on how to use this argument, visit: https://docs.trychroma.com/usage-guide Defaults to None. params_to_output: A list containing the parameters to output from the query. Defaults to ["distances", "uris", "embeddings"]. Returns: A list of EmbeddingData objects containing the matching results. """ if params_to_output is None: params_to_output = ["distances", "uris", "embeddings"] # retrieve the vector of the chosen image vector_embedding = self.retrieve_embeddings_of_images(images_ids=[image_id])[0] n_most_similar_to_vector = self.find_n_most_similar_to_vector( vector=vector_embedding, n=n, metadata_filters=metadata_filters, params_to_output=params_to_output, ) return n_most_similar_to_vectorIt simply becomes retrieving the embedding of a given image, and finding the results most similar to that vector. I hope you can appreciate how intuitive all of the syntax is.At this point is where I would strongly recommend testing out what you have built so far. Create a notebook and check out which images are similar to which, or which among your images CLIP thinks is the closest to the word “potato”. Let me show you some examples with my data.Let’s start with something easy. Let’s see what image comes up if we search for the word “forest” (I have also printed the distance for extra insights)Ok, pretty spot on I would say.I checked and couldn’t see any potatoes in my data sample, so now I’m genuinely curious to see what happens if we search for “potato”Ok well, it’s definitely not a potato, but given that there wasn’t any, not too bad. If you squint your eyes enough, it will start looking more and more like one. Jokes aside, the embeddings aren’t perfect, and that’s why it’s important to test them out and build some intuition for how they work.Let’s do a final test to see how similarity between images works. I’ve picked this floral depiction to test.And here are the most similar images to it:Of course, the most similar one is the image itself. And you can see that the distance is essentially zero. The second one is quite close to it semantically, and that is also reflected by the low distance. I would say we can feel confident we have built a solid system!We are now almost ready to wrap up. We have built all the essential functionalities, we have checked that they work as expected and we are all set to start building our recommender on top of it. Let’s discuss one more functionality that will be crucial for a good user experience.Retrieving diverse imagesLet’s say we have completed our recommender, it works beautifully and we are ready to release it. What would we show someone who logs in for the first time? This is the so-called cold start problem. There are many ways to solve it, usually based on what popular items you have on your app or what other users in the region have interacted with. But what if you don’t have that information because you are releasing the app for the very first time? We would probably go with a random selection of our items. But how would that experience be for our users?When I was trying this out in the initial tests, I was noticing that often the first random images were extremely similar to each other. This was mostly due to the fact that the underlying data had groups of images that were almost identical, because data from museum APIs can be structured in homogeneous groups. If you download fifty images from one museum only, they might all end up being Japanese prints. So how could we mend this issue such and avoid giving our users the impression that our data is extremely repetitive? We need to have a method to retrieve a heterogeneous set of artworks. Like any novice, I googled what methods are out there. And there is a well-established method to retrieve a group of diverse vectors called Maximal Marginal Relevance (MMR for short).MMRThe basic intuition is simple: start from a random embedding, then loop over your collection and select another vector having the least similarity to the one you have already retrieved. Repeat until you have extracted all the embeddings you wanted. Here is a good article that explains how it works and presents a use case. To make it concrete, below is the code I have implemented for our ChromaDB wrapper class:def mmr_vector_search(self, n: int = 10, lambda_param: float = 0.5) -> list[str]: """Perform a diverse vector search using MMR (Maximal Marginal Relevance). This function retrieves a set of n diverse vector IDs from the given ChromaDB collection using the MMR algorithm. It balances between relevance and diversity of the selected vectors. Args: n: Number of diverse vectors to return. Defaults to 10. lambda_param: Lambda parameter for MMR. Controls the trade-off between diversity (higher values) and similarity (lower values). Must be between 0 and 1. Defaults to 0.5. Returns: A list of n diverse vector IDs from the collection. Raises: ValueError: If lambda_param is not between 0 and 1. """ if not 0 raise ValueError("lambda_param must be between 0 and 1") # Get all embeddings and IDs from the collection result = self.collection.get(include=['embeddings']) all_embeddings = np.array(result['embeddings']) all_ids = result['ids'] # Initialize selected_ids = [] selected_embeddings = [] remaining_indices = list(range(len(all_ids))) # Select the first vector randomly first_index = np.random.choice(remaining_indices) selected_ids.append(all_ids[first_index]) selected_embeddings.append(all_embeddings[first_index]) remaining_indices.remove(first_index) # Select the rest using MMR for _ in range(1, n): if not remaining_indices: break best_score = float('-inf') best_index = -1 for idx in remaining_indices: candidate_embedding = all_embeddings[idx] # Compute similarity to selected embeddings # abs applied on a multidimensional object just takes the abs of each element sim_selected = np.abs(np.dot(candidate_embedding, np.array(selected_embeddings).T)) max_sim_selected = np.max(sim_selected) if len(sim_selected) > 0 else 0 # Compute diversity score # diversity_score = np.min(1 - sim_selected) if len(sim_selected) > 0 else 1 diversity_score = -1*max_sim_selected # Compute MMR score mmr_score = lambda_param * diversity_score - (1 - lambda_param) * max_sim_selected if mmr_score > best_score: best_score = mmr_score best_index = idx selected_ids.append(all_ids[best_index]) selected_embeddings.append(all_embeddings[best_index]) remaining_indices.remove(best_index) return selected_idsYou can see that the code is as simple as the concept: having a vector, start looping over your collection and retrieve the ones that have a higher diversity score. The full functionality of MMR is actually to balance relevance and diversity at the same time. So one can retrieve embeddings that are diverse among themselves while still being similar to an initial item. This is controlled via lambda_param in the function above. If we set it to 1 then we optimise for diversity only.Great, we have implemented our function and now we’re ready!Well… not quite. This is where it’s important to start thinking as a more experienced ML practitioner. The function above works, that’s true, but it’s slow. It loops over our entire collection, selects a vector and then repeats iteratively. If our collection consisted of millions of images, it would take extremely long for this process to complete.Retrieving diverse vectors efficientlyWhen I got to this point of the recommender, I was dissatisfied. Everything was working, but this final step bothered me. It felt like I could do better. But searching online I wasn’t able to find any straightforward method to gain significant efficiency while not compromising on readability and simplicity. And then it hit me that all I was doing here was interacting with a vector space. See, when I was working on this project, I spent a good amount of time thinking about CLIP. I was fascinated by the notion of mapping images and text onto the same vector space. Because of that I took my time brushing up on the basics of vector spaces, which I find a beautiful subject by themselves (probably due to my physics background). And when I was tackling this problem I got reminded that a vector space already has a set of vectors that span the space and are maximally diverse (i.e. orthogonal) to each other. These form the basis of the space. Sure one could say that two vectors pointing in opposite direction are actually more diverse than orthogonal ones. But I would argue otherwise. Up and down (which would be semantically opposite) are less diverse than up and left. After all, aren’t opposites intrinsically part of the same concept? I hope you see what I mean.Orthogonality is what adds a new dimension to a space, a new direction to explore. With this intuition in mind, we find ourselves already having a set of diverse vectors built into our collection. All we have to do is randomly select some of our basis vectors and get the artwork’s embedding closest to each, which is a functionality we have already implemented!Let’s look at the code:def efficient_diverse_vectors_retrieval( self, n: int = 40, image_paths_to_avoid: Optional[list[str]] = None ) -> list[str]: """Efficiently retrieve a set of diverse vectors from the collection. Diversity is defined as low absolute overlap of a vector with the selected ones. This method works by selecting a random set of basis directions and retrieving every time the closest vector in the collection to this random direction. Args: n: The number of ids to retrieve. Defaults to 40. image_paths_to_avoid: List of images not to be included in the output. Defaults to None. Returns: A set of diverse images. """ if image_paths_to_avoid is None: image_paths_to_avoid = [] selected_ids = [] # extract sample embedding for dimensionality # NOTE: this retrieves all embeddings in the collection. Can we optimise this? result = self.collection.get(include=['embeddings']) # Determine the dimensionality of your embeddings space dimensionality = len(result['embeddings'][0]) basis_vector = np.zeros(dimensionality).tolist() random_basis_dimensions = np.random.choice(a=dimensionality, size=n, replace=False) for basis_dimension in random_basis_dimensions: basis_vector[basis_dimension] = 1.0 new_id_not_found = True i = 1 while new_id_not_found: candidate = self.find_n_most_similar_to_vector(vector=basis_vector, n=i)[i - 1] i += 1 candidate_image_path = candidate.image_path if ( candidate_image_path not in selected_ids ) and ( candidate_image_path not in image_paths_to_avoid ): selected_ids.append(candidate_image_path) new_id_not_found = False basis_vector[basis_dimension] = 0.0 return selected_idsFirst of all, we retrieve the dimensionality of our embedding space (you can also hardcode this if you want to make it more efficient, but I wanted to keep it flexible). We then construct n random basis vectors, with n being the number of images we want to retrieve. It’s extremely simple: create a d-dimensional (with d being the dimensionality of CLIP’s embedding space) vector of zeroes with a 1 in a random spot. For this basis vector, retrieve the most similar embedding to it in our collection (a built-in functionality of our DB). Create another basis vector, repeat and voilà, we’re done. For completeness, I have also included the possibility of avoiding certain images, in case we might want to do this in our final app. Notice that we now only loop over the number of vectors we want to retrieve, not over our entire collection for each of the results.I encourage you to test this out, measure the runtime of the two methods when retrieving a hundred images. How about a thousand? How about ten thousand? Is the efficiency gain noticeable? And how do the images retrieved by the two compare? From the tests I ran, this new method was worth it. It lead to a visible runtime improvement, while maintaining a high degree of diversity. I was finally satisfied.The final caveatsI can’t end without mentioning two important caveats that come with the method above.The first one is that I built this method on top of the notion that we are working with a vector space. But is CLIP’s space a formal, well-defined vector space? I don’t know. If any of you have a good answer to this, please add it in the comments! I am genuinely curious. If we are not dealing with a proper vector space, what guarantees that orthogonality actually corresponds to semantic diversity? I don’t have a good answer to this, except for the fact that this concept is what gave me the intuition, but the decision to rely on this method came from the tests I ran with it. I adopted it because I observed that it actually led to diverse sets of artworks. So I invite you to take a look at the images and employ this method only if you are satisfied with it. As always, the decision should boil down to the impact on the final product.The second caveat is presented by the concept of representation collapse. What if CLIP ends up mapping all our artworks to a small region of the vector space? This essentially happens when the embedding model doesn’t capture the breadth of semantics contained in the data. If that is the case, all of our vectors end up inhabiting a subspace of the total embedding space. And when that is the case, we should actually select the basis vectors of said subspace, and not of the larger original embedding space. This is a tricky problem and it’s out of the scope of this article, but it’s a crucial aspect to keep in mind when dealing with embeddings. Again, this was not a blocker for me because of the reason mentioned above.Ok, phew, here we are. Congratulations for getting to this point. It was a dense article, and I hope you learnt something new along the way. Most of all, I hope that you are satisfied with the vector database you have built! Now it’s time to bring all of this work together and build a recommender system worthy of this effort. See you all in the final chapter!Build an Art Recommender from scratch with CLIP and ChromaDB was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.