Harry Potter and the Data Science Project
Using ML techniques to analyze Harry Potter’s relationships over time
Adiba Hasnat and Addie Pratt
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:
- Can we predict the final state of Harry’s relationship with a
character based on their early interactions?
- How do attributes like lineage, hair color, and gender influence
relationship dynamics with Harry?
- 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?
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
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.
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.
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”).
Handling missing values by replacing NA with
"Unknown" to ensure completeness.
Dropped unnecessary columns
Mapped and Consolidated Character Names
- Adjusted variations in character names for consistency (e.g., “James
Potter” → “James”, “Lily Potter” → “Lily”).
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.
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.
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:
- Hair Color Distribution: Analyze the distribution of characters’
hair colors in the dataset, excluding “Other.”
- Affection vs. Familiarity: Scatterplot showing Harry’s affection and
familiarity with each character, colored by gender.
- Lineage Distribution: Bar plot of characters’ lineages with Harry
Potter-themed colors.
- Positive vs Negative Relationships: Bar plot of characters grouped
by whether Harry’s affection towards them is positive or negative.
- 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:
Defining numerical attributes for intangible concepts such as
“closeness” or “familiarity” presented significant obstacles. These are
inherently subjective and difficult to quantify, which may introduce
biases or inaccuracies in the analysis.
Translation and data integrity issues were a persistent
challenge. Given the project’s origins in Hong Kong, much of the project
involved cleaning, consolidating, and correcting mistranslated or
inconsistent information to ensure the dataset’s usability and
reliability.
Modeling human connections, such as friendships or romantic
relationships, is inherently complex and prone to error. Human
interactions are influenced by numerous external and internal factors
that cannot be fully captured in a dataset, especially one derived from
fictional narratives.
The dataset is based on a fictional universe, which introduces
constraints in generalizing findings to real-world contexts. The
relationships and behaviors in the Harry Potter series may not reflect
realistic or nuanced human interactions.
A significant portion of the project was dedicated to cleaning
and consolidating the data. This effort highlights the inherent
messiness of datasets created through non-standardized processes,
particularly when human judgment and interpretation play a
role.
Predictive models, while insightful, cannot fully replicate the
nuances of human relationships as portrayed in a book series. Comparing
model predictions to the actual story outcomes emphasizes the
limitations of such models, even as they provide valuable
insights.
While the project offers interesting findings, its broader
applicability is constrained by the specific context of the Harry Potter
series. However, as digitalization increasingly influences areas like
finding friends, roommates, and romantic partners, efforts to analyze
and derive insights from relational data remain essential.
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
We can potentially have the ability to predict book endings,
character relationships, and responsive outcomes with machine learning
models.
Harry’s closest friends are Ron, Hermione, Neville, Ginny, and
Hagrid - mostly expected, but when breaking down their relationships in
different categories, it’s exciting to see!
We may be able to predict connections between people based on
previous data and lived experiences, which offer interesting
possibilities in the realm of digitalization - things such as forming
teams in the workplace, dating applications, and social
networking.
Future Plans
Looking forward, this project opens the door to several exciting
extensions and applications. Some of our future plans for this project
include:
Interactive Guessing Game: Develop an
interactive tool where users can input specific qualities of a character
(e.g., gender, lineage, appearance) and receive predictions about
Harry’s affection level toward them. This tool would use the existing
predictive model to simulate Harry’s potential reaction to new or
hypothetical characters.
Character Identification Game: Create a game
where users receive clues about a character’s attributes (e.g., lineage,
looks, or affiliation) and guess which character is being described.
This would make use of the dataset to generate engaging trivia-style
questions.
Relationship Prediction Tool: Expand the dataset
and predictive model to allow users to guess the type of relationship
Harry would have with a character based on their attributes. This could
include categories such as “friend,” “teammate,” “opponent,” or
“neutral.”
Improved Predictive Modeling: Refine the
predictive models used in the project to better account for subtle
nuances in relationships. This might involve experimenting with more
advanced machine learning techniques or incorporating additional data
sources.