Build an Art Recommender from Scratch with CLIP and ChromaDB
From the publisher’s feed, collected in the ZeroLabs newsroom.
Part III: The recommenderThe Merry Fiddler by Gerard van Honthorst, retrieved from the Rijksmuseum API.We’ve come to the final chapter of our journey. It’s time to put together everything we’ve built in part I and II of this series and create our recommender system. This is the part that is most subjective. I designed the system based on my vision, but that vision could have been completely different and so would have been the components and functionalities of this system. So let’s start from the idea I had in mind.The recommender system I wanted to build was something of a “Tinder for art”. Users would get presented with artworks, and be able to swipe left or right on them, expressing their preferences. This information would in turn be used to build a user profile, based on which a user would get not only recommendations for new artworks they might like, but also museums to visit in a specific city. Let’s dive into how I implemented this. Schematically, some of the ideal functionalities of the system would be:Showing artworks to the user, allowing them to like or dislike each.No item should be shown twice.The app should balance exploration and exploitation: showing new unseen artworks while also highlighting recommended ones.Having a personalised page where users can explore analytics related to their interactions, such as most liked author, style, material, location, etc.Providing recommended museums based on the user preferences and location.In this tutorial, we are not going to build all of this in a full-fledged manner. That would be enough material for three more articles at least. But we will go over some ideas on how to implement basic versions of these functionalities that integrate well with what we have already built. Let’s get started.User embeddingThe first question we need to answer is how do we choose which artworks to recommend?The main weapon in our arsenal is similarity. What if we simply start by recommending artworks similar to the ones the user interacted positively with? This is the most immediate approach we can start from. But as time goes by and a user interacts with more and more artworks, it will become increasingly complicated to perform this kind of calculation, since we are checking across all their likes. What if we condensed this information into one object that summarised the user’s taste? A method to streamline this process is to create a user embedding. At this point this seems a bit of an arbitrary choice, but hopefully I can demonstrate that it comes with a series of advantages. First of all, creating this embedding means we can represent users in the same vector space as artworks, allowing for a consistent and unified approach to treat all the entities in our system. Not only that, but it also enables us to use similarity search to retrieve recommended artworks, which is exactly what we wanted! Let’s look at some code to better understand the methodology.Here you can see a user class with a diverse set of functionalities that might be useful to handle users across the entire workflow of the app. For now, I want to focus on the code used to create the user embedding:def create_or_update_user_vector( self, list_of_new_liked_image_ids: list[str], list_of_new_disliked_image_ids: list[str], list_of_new_liked_vectors: list[float], list_of_new_disliked_vectors: list[float],) -> None: """Function to update the vector representation of a user (or create it if it has not been created previously). The method to create this vector is extremely simple and far from optimal. We simply add together all the vectors of the liked artworks and subtract the ones of the disliked artworks. The result is then normalised. Args: list_of_new_liked_image_ids (list[str]): The newly liked image ids. list_of_new_disliked_image_ids (list[str]): The newly disliked image ids. list_of_new_liked_vectors (list[float]): The vectors of the newly liked images. list_of_new_disliked_vectors (list[float]): The vectors of the newly disliked images. """ # remove potential duplicates in the lists of new image ids and vectors. list_of_new_liked_image_ids = [ image_id for image_id in list_of_new_liked_image_ids if ( image_id not in self.liked_artworks ) ] list_of_new_liked_vectors = [ vector for image_id, vector in zip( list_of_new_liked_image_ids, list_of_new_liked_vectors ) if image_id not in self.liked_artworks ] list_of_new_disliked_image_ids = [ image_id for image_id in list_of_new_disliked_image_ids if ( image_id not in self.disliked_artworks ) ] list_of_new_disliked_vectors = [ vector for image_id, vector in zip( list_of_new_disliked_image_ids, list_of_new_disliked_vectors ) if image_id not in self.disliked_artworks ] # add the newly liked and disliked images to the ones recorded for the user self.add_liked_artworks(new_liked_artworks=list_of_new_liked_image_ids) self.add_disliked_artworks(new_disliked_artworks=list_of_new_disliked_image_ids) # keep the vectors of the liked images and invert the ones of the disliked images list_of_new_liked_vectors = [np.array(vector) for vector in list_of_new_liked_vectors] list_of_new_disliked_vectors = [ np.array(vector) * (-1.0) for vector in list_of_new_disliked_vectors ] # combine the two lists into a final one to create the user vector total_list_of_vectors = list_of_new_liked_vectors + list_of_new_disliked_vectors if self.vector: # A hacky way to take into account previously seen artworks # simply add the user vector multiplied by how many artworks had been # previously used to create the vector. weighing_factor = ( len(self.liked_artworks) + len(self.disliked_artworks) - len(list_of_new_liked_vectors) - len(list_of_new_disliked_vectors) ) # added for now to be sure it's always a numpy array # can be removed once final structure has been determined user_vector_array = np.array(self.vector.copy()) existing_user_vector_scaled = user_vector_array * weighing_factor total_list_of_vectors += [existing_user_vector_scaled] # convert the resulting numpy array into a list of floats self.vector = create_normalized_vector(total_list_of_vectors).tolist() self.user_preferences_db.at[self.user_index, "user_vector"] = self.vectorLet’s start from the create part of this function, which gets invoked when the user does not yet have a vector associated to them (i.e. when self.vector is None). The function calculates their vector using the embeddings of the liked and disliked artworks. After inverting the embeddings of the disliked artworks, it calculates the average vector of all these inputs (using create_normalized_vector from the helper functions). Be mindful: we don’t simply use the embeddings of disliked artworks, we first invert them by placing a -1 in front of thm. This means that disliking an artwork is considered equivalent to liking the opposite (within the embedding space) of that artwork. This was a personal choice, so if it seems weird, feel free to replace it with different logic. The main reason why I did it this way was because I wanted to make use of the information provided by disliked items.In case the user already has a vector, we want to update it based on the new interactions that were not taken into consideration since the last update event. We could simply go ahead and look at all the previous interactions of the user, as well as the new ones, and compute the vector as done when creating it for the first time. However, this is inefficient. The user already has a vector that summarises their previous interactions, and we should make use of that. We can simply pretend that all the user’s previous likes were for artworks with that vector. Here is a simple example to make this clearer:Let’s say the user likes an artwork with embedding 4 and dislikes one with embedding 2 (I am using scalars here for simplicity, but the reasoning translates over to vectors as well). The user embedding would then become 1 using (4–2)/2 (i.e. after inverting the disliked embedding). If the user then likes a vector with embedding 1, we could calculate the new embedding explicitly as:4–2+1 = 3; 3/3 = 1Or via (1x2 + 1)/3 = 1, where we replaced the first two embeddings by the user embedding scaled by how many artworks were used to calculate that embedding.I hope you can see how this method simplifies the process as it no longer requires us to access all of the embeddings of the previous artworks, but only the user embedding.I am convinced there are more efficient methods to create the user embedding, and I invite you to explore them. If you come across a method that works better, comment it below!Now that we have put in the work, let’s see how this methodology works in practice. To retrieve the recommended images, we can simply use the function find_n_most_similar_to_vector from our ChromaDB class. Let’s say a user likes the three following artworks:And dislikes this one:The top three recommended artworks from our collection would be:This is where it all becomes extremely subjective. Are these artworks in line with the taste of the user? Without proper data collection from multiple users’ interactions there is no way to say it. But at least we have a strategy to get started. Different experiments could then fiddle around with some of the parameters involved here, and measure the impact on users’ interactions. Here is some inspiration:We could modify the weights assigned to liked and disliked artworks: Maybe instead of -1, disliked artworks could have a weight of -0.5.We could give more weight to recent artworks. All the artworks liked and disliked in this update could weigh twice as much on the final user embedding.We could introduce a new functionality where a user “super likes” an artwork, and that gives it extra weight.The options are wide and varied.Ok, we still have a lot to get through, so let’s keep going. At this point, we already have a functioning workflow:We retrieve an initial selection of varied artworks (using our efficient method to retrieve a set of diverse vectors).Get the image_path from each, and display the artwork.After they have interacted with a few different artworks, compute the user embedding.Retrieve and display the recommended images.Repeat (this time passing the list of liked and disliked vectors combined as image_paths_to_avoid in efficient_diverse_vectors_retrieval , to make sure we don’t show art they’ve already seen).But this is not satisfactory and feels a bit repetitive. So instead of replicating this process multiple times, let’s create a continuous stream of images.Personalised image queueMost recommendation engines work based on continuous streams rather than discrete processes. When you scroll on your feed, you experience it as a continuous stream that adapts instantly based on your interactions with it. We won’t get to that level here, but at least we can try some basic approach to it.If our goal is to create a queue that keeps the user engaged, recommends them relevant artworks while also allowing space for exploration, we could start by creating two queues:An exploration queue, where we keep a diverse set of imagesAn exploitation queue, where we keep recommended imagesWe can append images to these queues at regular intervals while the user is “swiping” on the app, adapting them based on the interactions.Now that we have these two queues, how do we combine them into one coherent stream? This is where it could start getting more complicated. So again let’s keep it simple. My idea was to keep this queue short so we can adjust it fast based on the user’s interactions. We keep a temperature parameter, that keeps track of the user’s engagement. If the temperature starts going down, it means the user is getting less engaged and thus we should start showing them more recommended artworks. When the temperature gets high, we can dare a bit more and let the user explore.Let’s look at the code contained here:from collections import dequefrom typing import Dequeimport randomdef create_user_queue( exploration_queue: Deque[str], exploitation_queue: Deque[str], temperature: float, output_queue_length: int, ) -> Deque[str]: """ Creates a user queue by sampling from exploration and exploitation queues based on a given temperature. This function combines items from two queues, `exploration_queue` and `exploitation_queue`, to form a new queue of a specified length. The selection of items from each queue is influenced by the `temperature` parameter, which determines the likelihood of choosing from the exploration queue over the exploitation queue. Args: exploration_queue (Deque[str]): A queue of items to explore. exploitation_queue (Deque[str]): A queue of items to exploit. temperature (float): A value between 0 and 1 that influences the probability of selecting from the exploration queue. A higher temperature increases the likelihood of exploration. output_queue_length (int): The desired length of the output queue. Must not exceed the total number of unique items available in both input queues. Returns: Deque[str]: A queue containing a mix of items from the exploration and exploitation queues, with a length equal to `output_queue_length`. Raises: ValueError: If `temperature` is not between 0 and 1. ValueError: If `output_queue_length` exceeds the number of unique items available in both queues. """ if not 0 raise ValueError("Temperature must be between 0 and 1") # Count truly available unique items unique_items_count = len(set(list(exploration_queue) + list(exploitation_queue))) if output_queue_length > unique_items_count: raise ValueError( f"Requested unique output length {output_queue_length} " f"exceeds available unique elements {unique_items_count}" ) seen_items = set() result = deque() while len(result) # Handle case when one queue is empty if not exploration_queue: source_queue = exploitation_queue elif not exploitation_queue: source_queue = exploration_queue # Both queues have items, use temperature to decide elif random.random() print("sampling from exploration queue") source_queue = exploration_queue else: print("sampling from exploitation queue") source_queue = exploitation_queue item = source_queue.popleft() if item not in seen_items: result.append(item) seen_items.add(item) return resultThe logic is straightforward. If either queue is empty, we fall back to the other. However, this should be an edge case and not the norm. When both queues have enough items, we sample randomly from each based on the temperature, as described above. I have used Deque as a data structure since it comes with a series of advantages for our needs. Have a look here for more details. We also ensure that the same item cannot be added twice, in case it was present in both queues.So there we have it, we just have to create the exploration queue using our method for diverse retrieval, and the exploitation queue by getting the user vector and retrieving the artworks most similar to it. We then feed both to the above function and create a personalised user queue that balances exploration and exploitation. You still have the freedom to decide how often the new preferences get taken into account to influence the user’s feed. For instance, you could set it up such that every ten interactions, the user vector is re-calculated, both (or only the exploitation) queues are updated, and then used to update the feed queue. And we have our continuous and adaptive stream of images! It wasn’t that hard after all.Recommending museumsWe now have a system that functions as an art recommender. But I want to introduce another functionality of our system that just works out of the box after what we’ve built. And that is the ability of recommending museums. Let’s see how to do that.Again, the core will be to use vector similarity. Creating vectors for museums is not trivial. It would be hard to do it based on the art they contain because that would mean accessing their collection, embedding all their artworks and perhaps creating some sort of average vector that represents that museum. But very few museums provide access to their collections via API, and thus we would be significantly limiting our options. We can, instead, use some text description of the museums. Recall that when we built our class to manage our vector DB, we included a functionality to embed text data, since CLIP is multi-modal. So here is what we can do:Write a short description for each museum we intend to add to our recommender (or use the one from their website)Create a new collection with our ChromDB wrapper class, where we pass museum names and descriptionsUse the user embedding to retrieve the museums whose embeddings are most similar to the user.As an example:from embeddings_creation.src.chroma_db_generator import ChromaDBGeneratorchroma_db_obj_txt = ChromaDBGenerator(collection_name="museum_descriptions_collection", images_path="", jsons_path="", include_data_loader=False)chroma_db_obj_txt.add_text_data_to_collection( ids=["rijks", "moco", "van_gogh", "stedelijk"], documents=[ "This museum contains a historical collection of Dutch art. Keywords are: history, classics, sculptures, harmony, balance, flemish, vivid colours, scenic paintings.", "This museum contains contemporary and street art: From Warhol to Banksy. Keywords are: dynamic, exciting, obscene, shocking, graffiti, political messages, pop art.", "This museum contains a vast collection of Van Gogh and impressionist paintings. Keywords are: contrasting colours, paintings with fluid depictions, views, flowers, still life paitnings, Japanese art.", "This museum contains modern art. Keywords are: installations, sculptures, variety, shocking, political messages.", ] )And then using the user vector and the above instance it simply becomes:museum_results = chroma_db_obj_txt.find_n_most_similar_to_vector( vector=user_vector, n=3, params_to_output=[], )for res in museum_results: print(res.id)And once again, in a couple of lines we added a pretty impressive extra feature. Our system can now recommend to users both artworks and museums to visit, based on their preferences.With a little extra effort, we can create a nice UI (LLMs can help), and maybe integrate the Google Maps API to get something like this:Pretty cool, right?Alright, it’s time to call it a day. Let’s take a moment to look back at where we started and everything we’ve built along the way. Starting from zero, we managed to create a system capable of recommending art and museums to users. We did this while relying only on open access images and metadata from trusted sources.From here on, there are many options to move forward. You can embed all of this in a nice UI and build a functioning app that really works as a sort of “Tinder for art”, as I mentioned at the beginning. There are a variety of possibilities for making the system more refined: from improving the way the user embedding is computed, to upgrading the embedding model for this use case by fine-tuning it on our data. It’s up to you now.Thank you to everyone who followed me along the way, and I hope you learned something new from all this. Till next time!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.