Hogwarts Castle

Harry Potter and the Data Science Project

Using ML techniques to analyze Harry Potter’s relationships over time

Adiba Hasnat and Addie Pratt



Harry Potter Background Information


Harry Potter is a novel and movie series about a boy who finds out he is a wizard. He goes to a wizarding school called Hogwarts, has many adventures, and has to defeat an evil Wizard at the end of the novels. Many different characters shape Harry’s life, and the overarching theme in this series considers the power of friendship, love, and loyalty between many complicated people in the face of evil and oppression.

It is the third most read book series globally, just behind the bible and quotations from the works of Mao Zedong.

Main Characters

Harry Potter

Harry Potter

The boy who lived. Main character.

Hermione Granger

Hermione Granger

One of Harry’s best friends.

Ron Weasley

Ron Weasley

Harry’s first and best friend at Hogwarts.

Severus Snape

Severus Snape

Potions Master at Hogwarts. A complex character who is both an antagonist and protector of Harry.

Draco Malfoy

Draco Malfoy

Harry’s bully/most disliked person at Hogwarts.

Voldemort

Voldemort

Harry’s enemy. He killed Harry’s parents and was thought to be destroyed, but wasn’t.


Project Background


The Harry Potter series, known for its rich storytelling and dynamic characters, has captivated audiences worldwide. From Harry’s loyal friendships to his intense conflicts, every interaction contributes to the series’ themes of love, loyalty, and resilience. But what if we could analyze and predict Harry’s relationships and interactions throughout the series using machine learning techniques? This project aims to explore that possibility.


Inspiration


This project draws inspiration from creative AI experiments, such as the “Harry Potter written by artificial intelligence” article, where neural networks attempted to generate a continuation of the Harry Potter series. These humorous yet insightful attempts highlighted the potential of AI in storytelling, particularly in modeling and predicting character interactions based on established narratives.

The Harry Potter Dialogue Project (HPD)

The Harry Potter Dialogue (HPD) project serves as a foundation for our work. HPD used scenes from the series to train a predictive model capable of generating responses to scene prompts. It analyzed:

  • Character Attributes: Traits like personality, lineage, and affiliations that define each character.
  • Quantified Relationships: The evolving relationships between Harry and other characters, measured across books and chapters.

For example, HPD could predict how Harry might respond to a conversation with Draco Malfoy in a given context, based on their rivalry and the tension built over time.


Why It Matters


This type of work can be applicable to many different industries and deliver key insights. While this project looked at the idea of responsive AI in terms of video games, where a player makes choices that affect npcs and the environment, we wanted to analyze it in the broader context of ML in literature and socialization networks such as dating apps.


Similar Projects


Here are some related projects and research that provide context and inspiration for this work:


Our Project Goals


This project seeks to answer questions like:


Data Cleaning/Processing


7 Excel Files (Attributes) → all_books_combined_attributes.csv

7 Excel Files (Relations) → all_books_combined_relations.csv

all_books_combined_attributes.csv + all_books_combined_relations.csv → merged_data.csv → updated_merged_data.csv

Steps

  1. Input Data

    • Collected 7 Excel files for Attributes and 7 Excel files for Relations, each representing data from the 7 books of the Harry Potter series.
  2. Combine Data

    • Merged the 7 Excel files for Attributes into a single dataset: all_books_combined_attributes.csv.
    • Merged the 7 Excel files for Relations into a single dataset: all_books_combined_relations.csv.
  3. Standardization

    • Ensured column names were consistent and descriptive across datasets (e.g., name, book, chapter).
    • Standardized categorical entries, such as normalizing values in the lineage column (e.g., “Pure blood wizard” → “Pureblood”).
  4. Handling missing values by replacing NA with "Unknown" to ensure completeness.

  5. Dropped unnecessary columns

  6. Mapped and Consolidated Character Names

    • Adjusted variations in character names for consistency (e.g., “James Potter” → “James”, “Lily Potter” → “Lily”).
  7. Merge Datasets

    • Combined all_books_combined_attributes.csv and all_books_combined_relations.csv into a single file, merged_data.csv, using shared keys: name, book, and chapter.
  8. Final Refinement

    • Addressed translation and encoding issues in the merged dataset and extracted “Hair_color” from the looks column and added a new column in the dataset to produce the final cleaned file: updated_merged_data.csv.

Data Dictionary


Exploratory Analysis/Visualization


In this section, we explore Harry’s relationships with characters in the dataset. We analyze trends in affection, lineage, gender, and friendship through visualizations and statistical models.

Visualizations:

  1. Hair Color Distribution: Analyze the distribution of characters’ hair colors in the dataset, excluding “Other.”
  2. Affection vs. Familiarity: Scatterplot showing Harry’s affection and familiarity with each character, colored by gender.
  3. Lineage Distribution: Bar plot of characters’ lineages with Harry Potter-themed colors.
  4. Positive vs Negative Relationships: Bar plot of characters grouped by whether Harry’s affection towards them is positive or negative.
  5. Predicted Probabilities by Gender: Violin plot showing the predicted probabilities of being Harry’s friend based on gender.

Hair Color Distribution

  • Displays the distribution of characters by hair color, excluding non-specific categories like “Other.”
  • Dark and black hair are the most common, while white and red hair are rare.
  • The diversity in hair colors reflects the varied personalities and appearances of the characters.

Affection vs. Familiarity

  • Explores the relationship between Harry’s affection for characters and his familiarity with them, categorized by gender.
  • Positive correlation exists between affection and familiarity, with most characters clustering around higher values.
  • Characters with whom Harry is more familiar tend to receive higher affection scores, highlighting the importance of shared experiences in forming bonds.

Lineage Distribution

  • This visualization showcases the distribution of characters across different lineages in the Harry Potter universe, based on their last appearance in the dataset.
  • Purebloods and Half-bloods dominate the dataset, reflecting their prominence in the series.
  • Lineages like Muggles and Mixed Giant are less frequent but represent unique and diverse interactions in the story.
  • Unknown lineage accounts for a noticeable proportion, indicating characters with undefined or ambiguous backgrounds.
  • This distribution highlights the socio-political dynamics of lineage within the Harry Potter universe, offering a lens to analyze biases and relationships shaped by ancestry.

Positive vs. Negative Relationships

  • Visualizes the distribution of characters with positive and negative relationships with Harry, considering only their last occurrence in the series.
  • The majority of characters exhibit positive relationships with Harry, with fewer in the negative category.
  • Harry’s social interactions lean towards positivity, aligning with his role as a central, likable protagonist in the series.

Predicted Probabilities of Friendships by Gender

  • This visualization explores how gender, along with Harry’s affection, influences the likelihood of a character being classified as Harry’s friend.
  • Female characters generally exhibit higher predicted probabilities of being Harry’s friends compared to male characters.
  • A few male characters show low probabilities, potentially indicating negative relationships or rivals.
  • The model suggests that gender and Harry’s affection levels play significant roles in predicting friendships, emphasizing how relationships in the Harry Potter universe are shaped by emotional bonds.


Answering Questions


1. Can we predict the final state of Harry’s relationship with a character based on their early interactions?

Key Insights:

  • Progression Analysis:
    • The first plot visualizes the actual progression of Harry’s affection from Book 1 to Book 7, while the second plot compares his affection from Book 1 to its predicted state in Book 7 based on early interactions (Books 1–3).
    • Key observations:
      • Hermione, Ron, and Hagrid showed positive growth in affection in both the actual and predicted plots, reflecting their deepening friendships.
      • Malfoy and Voldemort exhibited negative trends, aligning with their antagonistic roles, which were also accurately captured by the predictions.
      • Snape demonstrated a nuanced shift in both plots, reinforcing the complexity of his character and showcasing the model’s ability to account for some character intricacies.

Model Accuracy:

  • The model was trained on Harry’s interactions from Books 1–3 to predict his affection in Book 7. It achieved reasonable accuracy, with most predictions closely aligning with actual values. However, deviations for characters like Snape, Malfoy, and Voldemort highlight the limitations of using a linear regression approach to fully capture the nuanced and complex dynamics of character relationships.

Conclusions:

  • Early interactions provide a solid basis for predicting the nature of Harry’s relationships.
  • However, significant events in later books (e.g., plot twists or character development) may introduce deviations.
  • Future improvements could involve incorporating additional features such as character traits, major events, or interactions beyond Books 1–3.

2. How do attributes like lineage, hair color, and gender influence relationship dynamics with Harry?

  • Hair color emerges as the most influential attribute in predicting Harry’s relationships, suggesting that physical traits like hair color may hold symbolic or relational significance throughout the series.
  • Lineage and gender also contribute significantly, indicating that heritage and gender roles influence how characters interact with and are perceived by Harry.


Hair Analysis

  • High-affection characters tend to have red or brown hair, which aligns with key relationships, such as the Weasleys (notably Ron and Ginny).
  • Hair color diversity in low-affection characters is relatively uniform, showing no specific bias, reflecting that negative relationships are less influenced by physical attributes.


Lineage Analysis

  • Characters with high affection from Harry predominantly belong to pureblood lineage, reflecting his close connections with wizarding families (e.g., the Weasleys).
  • Low-affection characters are more distributed among muggle and half-blood lineages, indicating Harry’s mistrust or antagonism towards non-magical affiliations or prejudiced wizarding families.


Gender Analysis

  • Harry has high affection towards males, which can be attributed to his friendships with Ron, Hagrid, and Dumbledore.
  • Gender distribution in low-affection relationships is skewed towards males as well, primarily due to antagonistic figures like Voldemort and Malfoy.

3. Using attributes such as Familiarity with Harry and Affection for Harry, can we accurately predict whether a character falls into the category of friend, classmate, family member, opponent, enemy, etc?

  • Unfortunately, when trying to go about a kNN model for answering this question, we ran into issues that in the end would require significant data overhaul and cleaning - pretty much row by row translations, etc.

  • Below is our initial attempt at answering this question with a model, linear regression. Here are a few characters. These are still interesting to look at - for example, Snape may be more likely to be considered a classmate rather than a teacher.


Limitations


This project faced several notable challenges, largely stemming from the nature of the data and the complexity of modeling human behavior. Key limitations include:

By recognizing these limitations, the project demonstrates the challenges of working with subjective, messy, and context-specific data. These challenges also underscore the importance of carefully interpreting results and acknowledging the constraints of predictive modeling.


Key Insights/Takeaways



Future Plans


Looking forward, this project opens the door to several exciting extensions and applications. Some of our future plans for this project include: