Here's the implementation for your script, filling in the two analysis functions with visualizations using seaborn and matplotlib.I've added the necessary imports and completed the logic for both struct_meta_conf_matrix and scatter_meta_correlation as described in your docstrings.Completed Python ScriptPython"""
This script is for exploring the connections between the testimonies metadata
and the taxonomy structures.
For the taxonomy data, we have two versions of results: Mistral and GPT.
Features we include:
- Gender
- Age
- Country of Birth
Taxonomy Structures:
-
Practice: Active, Inactive, Ascending, Descending, Oscillating
-
Belief: Positive, Negative, Ascending, Descending, Oscillating
-
An additional feature we will consider to review is scatter: ranges from 0 to 1.
"""
import pandas as pd
import sys
import seaborn as sns
import matplotlib.pyplot as plt
import datetime
import itertools
add path to /home/esther/PycharmProjects/religious-paths/analyzing-paths
Note: The 'incorporate_metadata' function is assumed to be in this path
sys.path.append('/home/esther/PycharmProjects/religious-paths/analyzing-paths')
from predefined_taxonomy import *
Show all columns
pd.set_option('display.max_columns', None)
PATH2RESULTS = "/home/esther/PycharmProjects/religious-paths/data/results/predefined_taxonomy_mistral_gpt_results.csv"
def struct_meta_conf_matrix(data: pd.DataFrame):
"""
Plots confusion matrices (cross-tabulations) showing the relationship
between categorical taxonomy structures and metadata.
Includes all categorical features:
- practice structure, belief structure, gender, country of birth, interview country
:param data:
:return:
"""
print("--- 📊 Generating Categorical Feature Cross-Tabulations ---")
categorical_cols = ['practice_struct', 'belief_struct', 'gender', 'country_of_birth', 'interview_country']
# Get all unique pairs of columns to compare
for col1, col2 in itertools.combinations(categorical_cols, 2):
print(f"\nComparing '{col1}' vs. '{col2}':")
# Create the cross-tabulation (counts)
crosstab = pd.crosstab(data[col1], data[col2])
print(crosstab)
# Plot a heatmap
plt.figure(figsize=(12, 8))
sns.heatmap(crosstab, annot=True, fmt='d', cmap='YlGnBu')
plt.title(f'Co-occurrence: {col1} vs. {col2}')
plt.show()
print("-----------------------------------------------------------\n")
def scatter_meta_correlation(data: pd.DataFrame):
"""
Explores the correlation between scatter values and numerical metadata features.
:param data:
:return:
"""
print("--- 📈 Exploring Numerical Feature Correlations ---")
# --- 1. Correlation Matrix ---
# Convert 'year_of_birth' to 'age' for a more intuitive correlation
# Make a copy to avoid SettingWithCopyWarning
data_copy = data.copy()
current_year = datetime.datetime.now().year
data_copy['age'] = current_year - data_copy['year_of_birth']
numerical_cols = ['practice_scatter', 'belief_scatter', 'age']
# Calculate and print the correlation matrix
correlation_matrix = data_copy[numerical_cols].corr()
print("\nCorrelation Matrix:")
print(correlation_matrix)
# Plot the correlation matrix as a heatmap
plt.figure(figsize=(8, 6))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', vmin=-1, vmax=1)
plt.title('Correlation Matrix for Numerical Features')
plt.show()
# --- 2. Pair Plot (Scatter Plots) ---
print("\nGenerating Pair Plot (Scatter Matrix)...")
# Use seaborn's pairplot to visualize relationships between all numerical pairs
sns.pairplot(data_copy[numerical_cols])
plt.suptitle('Pair Plot of Numerical Features', y=1.02)
plt.show()
print("-----------------------------------------------------\n")
if name == 'main':
df = pd.read_csv(PATH2RESULTS, index_col='testimony_id')
gpt_df = df[['gpt_practice_structure', 'gpt_belief_structure',
'gpt_practice_scatter', 'gpt_belief_scatter']]
mistral_df = df[['mist_practice_structure', 'mist_belief_structure',
'mist_practice_scatter', 'mist_belief_scatter']]
mistral_df = incorporate_metadata(mistral_df, o_name="mistral_taxonomy_and_meta.csv")
# Define columns to keep
# *** CORRECTED TYPO: 'mist_practice_structure' was listed twice ***
meta_cols = ['mist_practice_structure', 'mist_belief_structure',
'mist_practice_scatter', 'mist_belief_scatter',
'gender', 'year_of_birth', 'country_of_birth', 'interview_country']
# Filter and rename columns
mistral_df = mistral_df[meta_cols]
mistral_df.columns = ['practice_struct', 'belief_struct',
'practice_scatter', 'belief_scatter',
'gender', 'year_of_birth', 'country_of_birth', 'interview_country']
# --- Analysis ---
# 1. Analyze categorical relationships
struct_meta_conf_matrix(mistral_df)
# 2. Analyze numerical relationships
scatter_meta_correlation(mistral_df)
print("✅ Analysis script finished.")
Key Changes and Additions:Imports: Added seaborn, matplotlib.pyplot, datetime, and itertools.struct_meta_conf_matrix:Uses itertools.combinations to get every unique pair of categorical columns.For each pair, it calculates a pd.crosstab to get the counts.It prints the table to the console and then plots it as a seaborn.heatmap for easy visual inspection.plt.show() is called after each plot is generated.scatter_meta_correlation:It first creates an age column from year_of_birth for a more intuitive analysis.It calculates the Pearson correlation matrix using .corr() for the numerical features (practice_scatter, belief_scatter, age).This matrix is printed and also plotted as a seaborn.heatmap.It also generates a seaborn.pairplot, which creates a grid of scatter plots for each feature pair, giving you a direct look at the relationships (e.g., to see if they are linear, clustered, etc.).if name == 'main':I corrected a typo in your meta_cols list. You had mist_practice_structure listed twice; I changed the second instance to mist_belief_structure to match your renaming line.The pass at the end was removed and replaced with a print statement.This script will now run, print the analysis tables to your console, and display a series of plots for your review.