Text Comparison with TF-IDF

Text Comparison with TF-IDF
Photo by Farzad / Unsplash

One very common scenario I've encountered as a business systems developer is the need to compare qualitative data from two or more sources to determine if there are similarities or matches.

For example, there is a collection of Contact records in our CRM that we want to match with a collection from an email list or marketing campaign. Contact names, emails, phone numbers, and other information may not be consistent and could have alternate spellings.

Or let's say users have been entering notes in a CRM about customers and the specific products they are interested in adopting. There is also a product request portal that is totally separate from the CRM, but needs to be aligned with the customer data. Is there a way to match existing descriptions between the portal and the CRM to make this connection?

While you could certainly do this type of matching manually, who wants to be the one do this level of tedious comparison? Fortunately, there are a lot of automated Natural Language Processing (NLP) methods we could employ, and I've happened across one such method recently I wanted to share because I found it to be particularly useful.

Term Frequency–Inverse Document Frequency (TF-IDF), is a numerical statistic that is intended to reflect how important a word is to a document in a collection or corpus. I'm not an expert regarding the mathematics supporting this strategy, and there is a lot of information readily available if you're interested in learning more or comparing various NLP strategies.

Instead, I want to focus on one specific application TF-IDF using scikit-learn's TfidfVectorizer to show how powerful it can be at comparing and relating qualitative data. While the applications of TF-IDF I came across demonstrated comparing a word or set of words to a collection of documents, I wanted to see what would happen if we compared documents to documents.

To illustrate this application, I started by asking a generative AI to come up with some writing prompt examples and then provide a short response to the prompt. The following table shows the original text responses:

id prompt text
1 Childhood memories When I was a child, my favorite memories were spent playing in the backyard with my friends. We would spend hours climbing trees, building forts, and having imaginary adventures. I remember the feeling of freedom and pure joy as we would explore the world around us. Those carefree days hold a special place in my heart and serve as a reminder of the importance of embracing our inner child.
2 Favorite book or movie One of my all-time favorite books is "To Kill a Mockingbird" by Harper Lee. The story beautifully captures the innocence of childhood and tackles important themes such as racism and injustice. The characters are so well-developed and the writing is both captivating and thought-provoking. It's a classic that continues to resonate with readers of all ages.
3 A place you would love to visit One place I have always dreamed of visiting is the Amalfi Coast in Italy. The stunning coastline, with its colorful cliffside villages and crystal-clear waters, is like something out of a dream. I imagine strolling along the narrow streets, indulging in delicious Italian cuisine, and soaking up the sun on the picturesque beaches. It would be a truly magical experience.
4 Describe your dream job My dream job would be to work as a travel writer. I have always had a passion for both writing and exploring new places, so combining the two would be a perfect fit for me. I imagine myself traveling to different countries, experiencing new cultures, and sharing my adventures through my words. I would love to inspire others to explore the world and appreciate its diversity through my writing.
5 The impact of technology on society Technology has revolutionized the way we live and interact with the world. From smartphones to social media, it has become an integral part of our daily lives. While it has brought numerous benefits such as increased connectivity and access to information, it has also raised concerns about privacy, mental health, and the digital divide. As technology continues to advance, it is important for society to navigate its impact and ensure its responsible and ethical use.
6 Diversity and inclusion Embracing diversity and promoting inclusion is crucial in building a more equitable and harmonious society. It is about recognizing and celebrating our differences, whether they be in terms of race, ethnicity, gender, sexual orientation, or abilities. By fostering an inclusive environment, we create opportunities for individuals to thrive and contribute their unique perspectives and talents. Diversity not only enriches our communities but also drives innovation and creativity. It allows us to learn from one another, challenge our assumptions, and create a more just and compassionate world. Embracing diversity and inclusion is not only a moral imperative but also a pathway to a brighter and more inclusive future.
7 How to overcome fear Fear is a natural human emotion that can often hold us back from reaching our full potential. However, it is possible to overcome fear and take control of our lives. One effective strategy is to confront our fears head-on and gradually expose ourselves to the things that trigger our fears. This process, known as exposure therapy, allows us to desensitize ourselves to the fear-inducing stimulus over time. Another helpful approach is to reframe our thoughts and beliefs about fear. Instead of viewing fear as a negative force, we can see it as an opportunity for growth and learning. By embracing fear and stepping outside of our comfort zones, we can discover our true capabilities and accomplish things we never thought possible. Ultimately, overcoming fear requires courage, resilience, and a willingness to face our fears head-on.
8 The importance of kindness Kindness is a powerful force that has the ability to transform lives and create a ripple effect of positivity. Simple acts of kindness, such as a smile, a compliment, or a helping hand - to someone in need, can brighten someone's day and make a lasting impact. Kindness not only benefits the recipient, but also the giver. Research has shown that performing acts of kindness can increase happiness, reduce stress, and improve overall well-being. It fosters a sense of connection and empathy, reminding us of our shared humanity. In a world that can often feel divided and disconnected, kindness has the power to bring us together and create a more compassionate society. Whether it's a small act of kindness or a larger endeavor, every act of kindness matters and has the potential to make a positive difference.
9 The future of renewable energy As the world faces the challenges of climate change and the finite nature of fossil fuels, the importance of renewable - energy has become increasingly evident. Renewable energy sources, such as solar, wind, and hydroelectric power, offer a sustainable and clean alternative to traditional forms of energy production. These sources are abundant and can be harnessed without depleting natural resources or emitting harmful greenhouse gases. The future of renewable energy lies in advancements in technology and infrastructure, as well as policy initiatives that encourage investment and adoption. As more countries and businesses recognize the benefits of renewable energy, we can expect to see increased innovation and a shift towards a more environmentally friendly and sustainable energy system.
10 The power of education Education is the key to personal and societal growth. It empowers individuals with knowledge and skills, opening doors to opportunities and improving quality of life. Education not only equips us with the tools to succeed but also fosters critical thinking, empathy, and a sense of global citizenship. It is a fundamental human right that should be accessible to all, regardless of background or socioeconomic status. Investing in education is investing in the future, as educated individuals drive innovation, advance society, and create a more equitable and just world.
11 The importance of mental health Mental health is just as important as physical health, yet it is often overlooked. Taking care of our mental well-being is crucial for overall wellness and happiness. It and managing our emotions, seeking support when needed, and practicing self-care. Mental health affects every aspect of our lives, from our relationships to our productivity. It is important to break the stigma surrounding mental health and promote open conversations about it. By prioritizing mental health, we can create a society that is compassionate, understanding, and supportive.
12 The role of technology in education Technology has transformed the field of education, providing new opportunities for learning and enhancing traditional teaching methods. It allows for personalized learning experiences, interactive lessons, and access to a diverse range of resources. Technology can make education more accessible, bridging the gap for students in remote areas or with limited resources. It also prepares students for the modern workforce, as technology skills are increasingly in demand. However, it is important to use technology in a balanced way, ensuring that it enhances education rather than replacing traditional teaching methods. Additionally, there are concerns about the digital divide, where not all students have equal access to technology, which can exacerbate existing inequalities. As technology continues to advance, it will play an increasingly important role in education, but it must be used thoughtfully and inclusively.
13 The value of lifelong learning Learning is not just confined to the classroom or specific periods of our lives. It is a continuous process that should be embraced throughout our lives. Lifelong learning allows us to adapt to changing circumstances, acquire new skills, and stay intellectually stimulated. It promotes personal growth, enhances career prospects, and encourages curiosity and exploration. Whether it's through formal education, online courses, workshops, or self-study, lifelong learning enables us to stay relevant in a rapidly evolving world.
14 The benefits of mindfulness Mindfulness is the practice of being fully present in the moment and non-judgmentally aware of one's thoughts, emotions, and sensations. It has been shown to reduce stress, improve focus and attention, and enhance overall well-being. Mindfulness can help to cultivate a sense of calm and clarity, allowing individuals to better manage their emotions and navigate life's challenges. It promotes self-awareness and encourages a non-reactive mindset, enabling individuals to respond to situations with intention and kindness. Mindfulness practices, such as meditation and deep breathing, can be incorporated into daily routines to foster a greater sense of peace and balance. By practicing mindfulness, we can cultivate a greater sense of gratitude for the present moment and develop a deeper connection with ourselves and others.
15 The importance of environmental conservation Environmental conservation is crucial for the future of our planet. It involves protecting and preserving ecosystems, biodiversity, and natural resources. By conserving the environment, we ensure the sustainability of essential services, such as clean air and water, food production, and climate regulation. Environmental conservation also plays a vital role in mitigating the impacts of climate change and preventing further ecological degradation. It requires collective action, including the adoption of sustainable practices, responsible consumption, and the protection of endangered species. Through conservation efforts, we can create a healthier and more resilient planet for future generations.
16 The significance of cultural diversity Cultural diversity refers to the range of different cultures, languages, traditions, and beliefs that exist in the world. It is important to recognize and celebrate cultural diversity, as it enriches our societies and promotes mutual understanding and respect. Cultural diversity encourages creativity, innovation, and the exchange of ideas. It challenges stereotypes and fosters inclusivity. By embracing cultural diversity, we can learn from one another and build bridges across differences. It is essential to promote intercultural dialogue and create spaces that value and appreciate diverse perspectives. Embracing cultural diversity contributes to a more harmonious and vibrant global community. It is a reminder of our shared humanity and the beauty of our collective heritage.
17 The power of empathy Empathy is the ability to understand and share the feelings of others. It plays a crucial role in fostering compassion, building relationships, and promoting social harmony. Empathy allows us to connect with others on a deeper level and create a sense of belonging. It helps to foster understanding and reduce conflicts. By practicing empathy, we can create a more inclusive and empathetic society where everyone feels seen, heard, and valued. interact with others. It provides a platform for sharing information, connecting with friends and family, and engaging with communities. However, it also has its drawbacks. The addictive nature of social media can lead to negative effects on mental
18 The impact of social media Social media has revolutionized the way we communicate and share information. It provides a platform for connecting with friends and family, engaging with communities, and staying informed about current events. Social media has also played a significant role in mobilizing social movements and raising awareness about important issues. However, it is important to recognize the potential negative effects of social media. The addictive nature of social media can have detrimental effects on mental health and well-being, leading to feelings of loneliness, comparison, and low self-esteem. Additionally, the spread of misinformation and the lack of privacy on social media platforms raise concerns about the impact on society and democracy. It is crucial to use social media responsibly, setting boundaries and being mindful of the information we consume and share.
19 Exploring different forms of art Art encompasses a wide range of creative expressions, including visual art, music, dance, theater, literature, and more. Engaging with different forms of art allows us to explore new perspectives, emotions, and ideas. It can inspire us, evoke strong emotions, and challenge our beliefs. Art also serves as a powerful tool for social commentary and cultural expression. By engaging with diverse art forms, we can broaden our horizons, appreciate different cultures, and foster creativity within ourselves. Whether it's visiting art galleries, attending performances, or creating our own art, exploring different forms of art can be a transformative and enriching experience.
20 The impact of poverty on individuals Poverty is a pervasive issue that affects millions of people around the world. It not only limits access to basic necessities such as food, shelter, and healthcare but also has profound social, emotional, and psychological consequences. Individuals living in poverty often face significant barriers to education and employment, perpetuating a cycle of generational poverty. Poverty can lead to increased levels of stress, anxiety, and depression, as individuals struggle to meet their basic needs and experience social exclusion. Moreover, poverty can also impact physical health, as limited resources may result in inadequate nutrition and healthcare. Addressing poverty requires comprehensive strategies that address systemic inequalities, provide access to quality education and healthcare, and promote economic opportunities for all individuals.
21 The importance of self-care Self-care refers to the practice of taking care of one's physical, mental, and emotional well-being. It involves prioritizing activities that promote relaxation, stress reduction, and personal growth. Self-care is essential for maintaining a healthy balance in life and preventing burnout. It includes activities such as regular exercise, getting enough sleep, practicing mindfulness and meditation, engaging in hobbies, and nurturing relationships. By practicing self-care, we can recharge and rejuvenate ourselves, improve our overall well-being, and better cope with the challenges and demands of daily life. It is important to prioritize self-care as an essential component of a healthy and fulfilling life.

Then I took those responses and asked the AI to create similar responses to the same topics, so I could get some text samples about the same general idea that were composed somewhat differently. I then rearranged the prompt-to-id mapping of the secondary responses:

id prompt text
1 The future of renewable energy As we look to the future, the potential of renewable energy is promising, but it will require concerted efforts in research, innovation, and collaboration. Embracing a mix of renewable energy sources and developing sustainable practices will be key to a greener and more eco-friendly future.
2 The power of education Education is indeed a powerful tool, but we must also acknowledge the systemic barriers that prevent equal access to quality education for all. Creating inclusive educational opportunities and addressing the root causes of educational disparities are essential for realizing the full potential of education as a catalyst for positive change.
3 The importance of kindness Kindness is a powerful force, and it's important to extend it not only to others but also to ourselves. Practicing self-kindness is essential for maintaining our well-being and enabling us to show genuine empathy and compassion to those around us.
4 A place you would love to visit I have always been drawn to the serene beauty of the Scandinavian fjords. The breathtaking landscapes, majestic waterfalls, and the opportunity to experience the unique Nordic culture make it a dream destination for me.
5 Favorite book or movie "The Great Gatsby" by F. Scott Fitzgerald holds a special place in my heart. The lavish parties, the mysterious Jay Gatsby, and the longing for unattainable dreams resonated deeply with me. It's a story that captures the essence of the Jazz Age and the complexities of human desires.
6 The impact of technology on society Technology's influence on society is undeniable, and while it has undoubtedly improved communication and access to information, we must also be mindful of its potential to disconnect us from genuine human connections. Balancing the benefits of technology with fostering meaningful face-to-face interactions is essential for a well-rounded society.
7 The importance of mental health Mental health should be treated with the same importance as physical health, and promoting mental well-being requires dismantling the stigma surrounding mental health issues. Engaging in open conversations, fostering supportive environments, and providing accessible mental health resources are crucial steps toward a healthier society.
8 The benefits of mindfulness Mindfulness practices can indeed promote well-being, but it's essential to recognize that different individuals may find solace in diverse forms of meditation or mindfulness techniques. Embracing a range of practices allows for a more inclusive and accessible approach to well-being.
9 The importance of environmental conservation Environmental conservation is imperative for the health of our planet, but we must also recognize the intersectionality of environmental issues with social justice. Addressing environmental challenges must include efforts to uplift marginalized communities disproportionately affected by environmental degradation.
10 The power of empathy Empathy can indeed foster compassion, but it's also crucial to couple empathy with active listening and tangible actions to support others. Combining empathy with genuine efforts to create positive change can lead to more meaningful impact.
11 The role of technology in education While technology can enhance education, we must be mindful of its potential to exacerbate educational inequalities. Ensuring equitable access to technology and promoting responsible usage will be essential in harnessing its full potential for educational advancement.
12 Childhood memories In my childhood, some of my fondest memories were of playing imaginative games with my siblings indoors during rainy days. We would create elaborate make-believe worlds, transforming our living room into magical kingdoms or outer space adventures. The joy and laughter we shared brought us closer together, and those cherished moments continue to put a smile on my face.
13 The value of lifelong learning Lifelong learning indeed fosters personal growth, but it's also vital to recognize that learning can occur in various forms and settings outside of formal education. Embracing a broad perspective on learning allows us to appreciate the different pathways to knowledge and wisdom.
14 How to overcome fear Overcoming fear is a personal journey, and while confronting our fears head-on can be empowering for some, others may find solace in gradual self-compassion and patience. Recognizing that everyone's fears and coping mechanisms differ allows us to support each other in our individual paths to conquering fear.
15 Diversity and inclusion Recognizing and celebrating our differences is crucial for fostering an inclusive society, but we must also acknowledge the intersections of identities that shape our experiences. Embracing diversity requires addressing the unique challenges faced by individuals with multiple marginalized identities and ensuring their voices are heard and uplifted.
16 The impact of social media While social media facilitates connectivity, it's important to address the echo chambers and filter bubbles that can perpetuate misinformation and reinforce pre-existing beliefs. Encouraging critical thinking and media literacy are crucial for navigating the complexities of social media.
17 Exploring different forms of art Art indeed offers diverse perspectives, but it's also essential to recognize the historical underrepresentation of certain artists and art forms. Supporting marginalized artists and promoting their works helps create a more inclusive and equitable artistic landscape.
18 The impact of poverty on individuals Poverty's effects are far-reaching, but it's also essential to address the structural factors that perpetuate poverty and inequality. Combining individual support with systemic change is necessary for breaking the cycle of poverty.
19 The importance of self-care While self-care is crucial, it's also essential to recognize that the ability to engage in self-care can be influenced by systemic barriers and societal expectations. Advocating for equitable access to self-care resources and promoting work-life balance benefits everyone in society.
20 Describe your dream job My ideal career would be as a wildlife conservationist. Being able to work directly with endangered species, protecting their habitats, and advocating for their preservation would be incredibly rewarding. The opportunity to make a positive impact on the natural world and contribute to the well-being of our planet is what motivates me.
21 The significance of cultural diversity Celebrating cultural diversity also involves recognizing the histories of colonization and cultural appropriation that have impacted many communities. Promoting cultural diversity requires dismantling oppressive systems and uplifting marginalized voices.

So now I have unique blobs of text that are about the same set of core topics across two different data sets. Here are some specific examples from the two sets:

Childhood Memories

Original Text: When I was a child, my favorite memories were spent playing in the backyard with my friends. We would spend hours climbing trees, building forts, and having imaginary adventures. I remember the feeling of freedom and pure joy as we would explore the world around us. Those carefree days hold a special place in my heart and serve as a reminder of the importance of embracing our inner child.

Secondary Text: In my childhood, some of my fondest memories were of playing imaginative games with my siblings indoors during rainy days. We would create elaborate make-believe worlds, transforming our living room into magical kingdoms or outer space adventures. The joy and laughter we shared brought us closer together, and those cherished moments continue to put a smile on my face.

The Benefits of Mindfulness

Original Text: Mindfulness is the practice of being fully present in the moment and non-judgmentally aware of one's thoughts, emotions, and sensations. It has been shown to reduce stress, improve focus and attention, and enhance overall well-being. Mindfulness can help to cultivate a sense of calm and clarity, allowing individuals to better manage their emotions and navigate life's challenges. It promotes self-awareness and encourages a non-reactive mindset, enabling individuals to respond to situations with intention and kindness. Mindfulness practices, such as meditation and deep breathing, can be incorporated into daily routines to foster a greater sense of peace and balance. By practicing mindfulness, we can cultivate a greater sense of gratitude for the present moment and develop a deeper connection with ourselves and others.

Secondary Text: Mindfulness practices can indeed promote well-being, but it's essential to recognize that different individuals may find solace in diverse forms of meditation or mindfulness techniques. Embracing a range of practices allows for a more inclusive and accessible approach to well-being.

Now for the processing and comparison. First, lets import pandas, numpy, and TfidfVectorizer from scikit-learn. Then create two DataFrames, one from the original responses and another for the secondary.

import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer


original = pd.read_csv('original_responses.csv')
secondary = pd.read_csv('secondary_responses.csv')

Next, while iterating through the rows of the original responses, we create the corpus of text samples to compare. This is just a list of the current text we're looking at and the entire collection of the secondary text responses.

for row in original.itertuples():
    id = row[1]
    prompt = row[2]
    text = row[3]

    corpus = [text]
    corpus.extend(secondary['text'].tolist())

Using the vectorizer we can now run the TF-IDF comparison, and transform the result matrices into a numpy array. From there we do a little cleanup to eliminate the comparison result of the text to itself, which would be a perfect match.

    vectorizer = TfidfVectorizer(min_df=1, stop_words='english')
    tfidf = vectorizer.fit_transform(corpus)
    pairwise_similarity = tfidf * tfidf.T

    arr = pairwise_similarity.toarray()
    np.fill_diagonal(arr, np.nan)

    input_idx = corpus.index(text)
    result_idx = np.nanargmax(arr[input_idx])

Finally, we can extract the matched text and trace it using its index in the secondary DataFrame.

    match_text = corpus[result_idx]

    match_idx = secondary['text'].str.find(match_text).to_list().index(0)
    match_id = secondary.iloc[match_idx]['id']
    match_prompt = secondary.iloc[match_idx]['prompt']

Using TF-IDF I was able to match the secondary text to the original text 100% of the time! I dropped the original prompt and the prompt from the matched text into a DataFrame with the output:

original_prompt match_prompt
Childhood memories Childhood memories
Favorite book or movie Favorite book or movie
A place you would love to visit A place you would love to visit
Describe your dream job Describe your dream job
The impact of technology on society The impact of technology on society
Diversity and inclusion Diversity and inclusion
How to overcome fear How to overcome fear
The importance of kindness The importance of kindness
The future of renewable energy The future of renewable energy
The power of education The power of education
The importance of mental health The importance of mental health
The role of technology in education The role of technology in education
The value of lifelong learning The value of lifelong learning
The benefits of mindfulness The benefits of mindfulness
The importance of environmental conservation The importance of environmental conservation
The significance of cultural diversity The significance of cultural diversity
The power of empathy The power of empathy
The impact of social media The impact of social media
Exploring different forms of art Exploring different forms of art
The impact of poverty on individuals The impact of poverty on individuals
The importance of self-care The importance of self-care

I'm sure there are some limitations, but in the cases where I have used this approach I've seen a pretty solid success rate. I look forward to exploring more and discovering new methods of text comparison that can deliver solid results without a ton of manual work.