
Image by Author | ChatGPT
Once you’ve identified potential interaction effects through visualization, the next step involves formally incorporating these interactions into your regression models. Adding interaction terms allows you to capture how the relationship between variables changes across different conditions, leading to more accurate predictions and deeper insights into your data patterns.
This tutorial demonstrates how to manually create and implement the three main types of interaction terms: numerical × numerical, numerical × categorical, and categorical × categorical interactions.
Prerequisites and Setup
You’ll need just a few essential Python libraries for regression modeling with interaction terms:
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, r2_score
We’ll create a simplified dataset that clearly demonstrates each type of interaction without unnecessary complexity.
# Create dataset with clear interaction patterns
np.random.seed(42)
n = 250
# Generate base variables
experience = np.random.uniform(0, 20, n)
age = np.random.uniform(22, 65, n)
education = np.random.choice(['High School', 'Bachelor', 'Graduate'], n, p=[0.4, 0.4, 0.2])
department = np.random.choice(['Sales', 'Engineering'], n, p=[0.5, 0.5])
# Create salary with built-in interactions
base_salary = 45000
salary = (base_salary +
2000 * experience + # main effect of experience
500 * age + # main effect of age
5000 * (education == 'Bachelor') +
10000 * (education == 'Graduate') +
8000 * (department == 'Engineering') +
# Interaction effects we'll learn to capture
100 * experience * age + # numerical × numerical
800 * experience * (education == 'Graduate') + # numerical × categorical
3000 * (education == 'Graduate') * (department == 'Engineering') + # categorical × categorical
np.random.normal(0, 5000, n))
df = pd.DataFrame({
'experience': experience,
'age': age,
'education': education,
'department': department,
'salary': salary
})
This simplified dataset contains three types of interactions that we’ll learn to implement and interpret.
Understanding Interaction Types
Before diving into implementation, let’s understand what each interaction type means:
Numerical × Numerical: The effect of one number depends on the value of another number. For example, the salary boost from experience might be stronger for older workers.
Numerical × Categorical: The effect of a number depends on which group someone belongs to. For example, each year of experience might provide bigger salary increases for graduate-degree holders.
Categorical × Categorical: The effect of being in one group depends on which other group you’re also in. For example, having a graduate degree might provide extra benefits specifically in engineering roles.
Method 1: Numerical × Numerical Interactions
Let’s start with the simplest case: when two numerical variables interact. This means the effect of one variable changes based on the value of another variable.
# Create a copy for our first interaction model
df_numeric = df.copy()
# Manually create the interaction term
df_numeric['experience_age_interaction'] = df_numeric['experience'] * df_numeric['age']
print("New interaction term created:")
print(f"experience_age_interaction range: {df_numeric['experience_age_interaction'].min():.1f} to {df_numeric['experience_age_interaction'].max():.1f}")
New interaction term created: experience_age_interaction range: 2.5 to 1252.6
Now let’s fit a model with and without the interaction to see the difference:
# Model WITHOUT interaction
X_no_interaction = df_numeric[['experience', 'age']]
y = df_numeric['salary']
model_basic = LinearRegression()
model_basic.fit(X_no_interaction, y)
# Model WITH interaction
X_with_interaction = df_numeric[['experience', 'age', 'experience_age_interaction']]
model_interaction = LinearRegression()
model_interaction.fit(X_with_interaction, y)
# Compare performance
basic_score = model_basic.score(X_no_interaction, y)
interaction_score = model_interaction.score(X_with_interaction, y)
print("Model Performance Comparison:")
print(f"Without interaction: R² = {basic_score:.4f}")
print(f"With interaction: R² = {interaction_score:.4f}")
print(f"Improvement: {interaction_score - basic_score:.4f}")
Model Performance Comparison: Without interaction: R² = 0.9265 With interaction: R² = 0.9557 Improvement: 0.0292
The R² improvement of 0.0292 demonstrates that accounting for the age-experience interaction meaningfully enhances our model’s predictive power.
Interpreting Numerical × Numerical Interactions
The interaction coefficient tells us how the effect of one variable changes as the other variable increases:
print("\nCoefficient Interpretation:")
print(f"Experience effect: ${model_interaction.coef_[0]:,.0f} per year")
print(f"Age effect: ${model_interaction.coef_[1]:,.0f} per year")
print(f"Interaction effect: ${model_interaction.coef_[2]:,.0f}")
Coefficient Interpretation: Experience effect: $2,086 per year Age effect: $539 per year Interaction effect: $101
The interaction coefficient (+$101) shows that the salary benefit from experience increases with age. Specifically, the experience effect starts at \$2,086 per year (when age = 0) and increases by \$101 for each additional year of age. Similarly, the age effect depends on experience level – it starts at \$539 per year (when experience = 0) and increases by \$101 for each additional year of experience. For example, a 30-year-old gains \$2,086 + (30 × \$101) = \$5,116 per year of experience, while a 50-year-old gains \$2,086 + (50 × \$101) = \$7,136 per year of experience.
Method 2: Numerical × Categorical Interactions
Now let’s handle interactions between numerical and categorical variables. This requires creating dummy variables first, then multiplying them by the numerical variable.
# Create dummy variables for education df_cat_num = df.copy() df_cat_num['education_bachelor'] = (df_cat_num['education'] == 'Bachelor').astype(int) df_cat_num['education_graduate'] = (df_cat_num['education'] == 'Graduate').astype(int) # Note: High School becomes the reference category (all zeros)
Create the interaction terms by multiplying experience with each education dummy:
# Create numerical × categorical interactions
df_cat_num['exp_bachelor'] = df_cat_num['experience'] * df_cat_num['education_bachelor']
df_cat_num['exp_graduate'] = df_cat_num['experience'] * df_cat_num['education_graduate']
print("\nInteraction terms created:")
print("exp_bachelor: experience effect for Bachelor degree holders")
print("exp_graduate: experience effect for Graduate degree holders")
print("(High School is the reference - no separate interaction term needed)")
Interaction terms created: exp_bachelor: experience effect for Bachelor degree holders exp_graduate: experience effect for Graduate degree holders (High School is the reference - no separate interaction term needed)
Fit models to compare the impact:
# Model without interactions
X_basic_cat = df_cat_num[['experience', 'education_bachelor', 'education_graduate']]
y = df_cat_num['salary']
model_basic_cat = LinearRegression()
model_basic_cat.fit(X_basic_cat, y)
# Model with interactions
X_interaction_cat = df_cat_num[['experience', 'education_bachelor', 'education_graduate',
'exp_bachelor', 'exp_graduate']]
model_interaction_cat = LinearRegression()
model_interaction_cat.fit(X_interaction_cat, y)
# Compare performance
basic_cat_score = model_basic_cat.score(X_basic_cat, y)
interaction_cat_score = model_interaction_cat.score(X_interaction_cat, y)
print("Numerical × Categorical Model Comparison:")
print(f"Without interaction: R² = {basic_cat_score:.4f}")
print(f"With interaction: R² = {interaction_cat_score:.4f}")
print(f"Improvement: {interaction_cat_score - basic_cat_score:.4f}")
Numerical × Categorical Model Comparison: Without interaction: R² = 0.7465 With interaction: R² = 0.7540 Improvement: 0.0074
While the improvement is smaller here (0.0074), it reveals important differences in how education levels respond to experience gains.
Interpreting Numerical × Categorical Interactions
These interactions show how the numerical variable’s effect differs across groups:
print("\nNumerical × Categorical Coefficient Interpretation:")
print(f"Base experience effect (High School): ${model_interaction_cat.coef_[0]:,.0f} per year")
print(f"Additional bachelor effect: ${model_interaction_cat.coef_[1]:,.0f}")
print(f"Additional graduate effect: ${model_interaction_cat.coef_[2]:,.0f}")
print(f"Extra experience benefit for Bachelor: ${model_interaction_cat.coef_[3]:,.0f} per year")
print(f"Extra experience benefit for Graduate: ${model_interaction_cat.coef_[4]:,.0f} per year")
print(f"\nTotal experience effects by education level:")
high_school_exp_effect = model_interaction_cat.coef_[0]
bachelor_exp_effect = model_interaction_cat.coef_[0] + model_interaction_cat.coef_[3]
graduate_exp_effect = model_interaction_cat.coef_[0] + model_interaction_cat.coef_[4]
print(f"High School: ${high_school_exp_effect:,.0f} per year of experience")
print(f"Bachelor: ${bachelor_exp_effect:,.0f} per year of experience")
print(f"Graduate: ${graduate_exp_effect:,.0f} per year of experience")
Numerical × Categorical Coefficient Interpretation: Base experience effect (High School): $6,171 per year Additional bachelor effect: $4,355 Additional graduate effect: $5,954 Extra experience benefit for Bachelor: $-154 per year Extra experience benefit for Graduate: $1,543 per year Total experience effects by education level: High School: $6,171 per year of experience Bachelor: $6,017 per year of experience Graduate: $7,714 per year of experience
The interaction coefficients show how the experience effect differs by education level. The base experience effect is \$6,171 per year for high school graduates. Bachelor’s degree holders get \$154 less benefit per year of experience (net effect: \$6,017), while graduate degree holders get an additional \$1,543 benefit per year of experience (net effect: \$7,714).
Method 3: Categorical × Categorical Interactions
Finally, let’s handle interactions between two categorical variables. This shows how being in one group affects the benefit of being in another group.
# Create dummy variables for both categorical variables df_cat_cat = df.copy() # Education dummies (High School is reference) df_cat_cat['education_bachelor'] = (df_cat_cat['education'] == 'Bachelor').astype(int) df_cat_cat['education_graduate'] = (df_cat_cat['education'] == 'Graduate').astype(int) # Department dummy (Sales is reference) df_cat_cat['dept_engineering'] = (df_cat_cat['department'] == 'Engineering').astype(int)
Create the categorical × categorical interaction:
# Create categorical × categorical interactions
df_cat_cat['bachelor_engineering'] = df_cat_cat['education_bachelor'] * df_cat_cat['dept_engineering']
df_cat_cat['graduate_engineering'] = df_cat_cat['education_graduate'] * df_cat_cat['dept_engineering']
print("\nCategorical × Categorical interactions created:")
print("bachelor_engineering: extra effect for Bachelor + Engineering combination")
print("graduate_engineering: extra effect for Graduate + Engineering combination")
Categorical × Categorical interactions created: bachelor_engineering: extra effect for Bachelor + Engineering combination graduate_engineering: extra effect for Graduate + Engineering combination
Compare models with and without categorical interactions:
# Model without categorical interactions
X_basic_cat2 = df_cat_cat[['education_bachelor', 'education_graduate', 'dept_engineering']]
y = df_cat_cat['salary']
model_basic_cat2 = LinearRegression()
model_basic_cat2.fit(X_basic_cat2, y)
# Model with categorical interactions
X_interaction_cat2 = df_cat_cat[['education_bachelor', 'education_graduate', 'dept_engineering',
'bachelor_engineering', 'graduate_engineering']]
model_interaction_cat2 = LinearRegression()
model_interaction_cat2.fit(X_interaction_cat2, y)
# Compare performance
basic_cat2_score = model_basic_cat2.score(X_basic_cat2, y)
interaction_cat2_score = model_interaction_cat2.score(X_interaction_cat2, y)
print("Categorical × Categorical Model Comparison:")
print(f"Without interaction: R² = {basic_cat2_score:.4f}")
print(f"With interaction: R² = {interaction_cat2_score:.4f}")
print(f"Improvement: {interaction_cat2_score - basic_cat2_score:.4f}")
Categorical × Categorical Model Comparison: Without interaction: R² = 0.0736 With interaction: R² = 0.0917 Improvement: 0.0181
This modest R² improvement (0.0181) masks dramatic salary differences that emerge when education and department combine.
Interpreting Categorical × Categorical Interactions
These interactions show extra effects when someone belongs to specific combinations of groups:
print("\nCategorical × Categorical Coefficient Interpretation:")
print(f"Bachelor degree effect: ${model_interaction_cat2.coef_[0]:,.0f}")
print(f"Graduate degree effect: ${model_interaction_cat2.coef_[1]:,.0f}")
print(f"Engineering department effect: ${model_interaction_cat2.coef_[2]:,.0f}")
print(f"Bachelor x Engineering interaction: ${model_interaction_cat2.coef_[3]:,.0f}")
print(f"Graduate x Engineering interaction: ${model_interaction_cat2.coef_[4]:,.0f}")
print(f"\nTotal effects for each education/department combination:")
print("Reference (High School + Sales): $0")
print(f"High School + Engineering: ${model_interaction_cat2.coef_[2]:,.0f}")
print(f"Bachelor + Sales: ${model_interaction_cat2.coef_[0]:,.0f}")
print(f"Bachelor + Engineering: ${model_interaction_cat2.coef_[0] + model_interaction_cat2.coef_[2] + model_interaction_cat2.coef_[3]:,.0f}")
print(f"Graduate + Sales: ${model_interaction_cat2.coef_[1]:,.0f}")
print(f"Graduate + Engineering: ${model_interaction_cat2.coef_[1] + model_interaction_cat2.coef_[2] + model_interaction_cat2.coef_[4]:,.0f}")
Categorical × Categorical Coefficient Interpretation: Bachelor degree effect: $6,519 Graduate degree effect: $8,811 Engineering department effect: $4,385 Bachelor x Engineering interaction: $21,330 Graduate x Engineering interaction: $28,975 Total effects for each education/department combination: Reference (High School + Sales): $0 High School + Engineering: $4,385 Bachelor + Sales: $6,519 Bachelor + Engineering: $32,234 Graduate + Sales: $8,811 Graduate + Engineering: $42,172
The interaction coefficients show additional effects beyond what you’d expect from simply adding education and department effects. For example, a Graduate + Engineering combination provides \$42k total benefit, which includes the graduate effect (\$8,811) + engineering effect (\$4,385) + an additional interaction bonus (\$28,975) that only occurs when both conditions are met.
Complete Example: Combining All Interaction Types
Let’s build a comprehensive model that includes all three types of interactions to see their combined effect:
# Create a dataset with all interaction terms
df_complete = df.copy()
# Create all dummy variables
df_complete['education_bachelor'] = (df_complete['education'] == 'Bachelor').astype(int)
df_complete['education_graduate'] = (df_complete['education'] == 'Graduate').astype(int)
df_complete['dept_engineering'] = (df_complete['department'] == 'Engineering').astype(int)
# Create all interaction terms
df_complete['exp_age'] = df_complete['experience'] * df_complete['age']
df_complete['exp_bachelor'] = df_complete['experience'] * df_complete['education_bachelor']
df_complete['exp_graduate'] = df_complete['experience'] * df_complete['education_graduate']
df_complete['bachelor_eng'] = df_complete['education_bachelor'] * df_complete['dept_engineering']
df_complete['graduate_eng'] = df_complete['education_graduate'] * df_complete['dept_engineering']
# Compare baseline vs full interaction model
X_baseline = df_complete[['experience', 'age', 'education_bachelor', 'education_graduate', 'dept_engineering']]
X_full = df_complete[['experience', 'age', 'education_bachelor', 'education_graduate', 'dept_engineering',
'exp_age', 'exp_bachelor', 'exp_graduate', 'bachelor_eng', 'graduate_eng']]
y = df_complete['salary']
# Split data for proper evaluation
X_base_train, X_base_test, y_train, y_test = train_test_split(X_baseline, y, test_size=0.2, random_state=42)
X_full_train, X_full_test, _, _ = train_test_split(X_full, y, test_size=0.2, random_state=42)
# Fit models
baseline_model = LinearRegression()
baseline_model.fit(X_base_train, y_train)
full_model = LinearRegression()
full_model.fit(X_full_train, y_train)
# Evaluate on test set
baseline_pred = baseline_model.predict(X_base_test)
full_pred = full_model.predict(X_full_test)
baseline_r2 = r2_score(y_test, baseline_pred)
full_r2 = r2_score(y_test, full_pred)
baseline_rmse = np.sqrt(mean_squared_error(y_test, baseline_pred))
full_rmse = np.sqrt(mean_squared_error(y_test, full_pred))
print("Final Model Comparison:")
print(f"Baseline model (no interactions): R² = {baseline_r2:.4f}, RMSE = ${baseline_rmse:,.0f}")
print(f"Full model (all interactions): R² = {full_r2:.4f}, RMSE = ${full_rmse:,.0f}")
print(f"Improvement from interactions: ΔR² = {full_r2 - baseline_r2:.4f}, ΔRMSE = ${baseline_rmse - full_rmse:,.0f}")
Final Model Comparison: Baseline model (no interactions): R² = 0.9601, RMSE = $8,219 Full model (all interactions): R² = 0.9885, RMSE = $4,414 Improvement from interactions: ΔR² = 0.0284, ΔRMSE = $3,805
The combined interaction model achieves excellent performance with nearly $4k reduction in prediction errors, demonstrating how multiple interaction types work together to capture complex salary relationships.
Key Takeaways and Best Practices
Start Simple: Begin with one interaction type and understand it thoroughly before adding complexity.
Use Domain Knowledge: Create interactions that make business or scientific sense rather than adding every possible combination.
Check for Improvement: Always compare models with and without interactions to ensure they’re actually helping.
Interpret Carefully: Interaction coefficients modify main effects – they don’t represent standalone impacts.
Watch for Multicollinearity: Interaction terms are mathematically related to their component variables, which can cause interpretation issues in some cases.
Conclusion
Manual creation of interaction terms provides the clearest path to understanding how variables work together in regression models. By systematically working through numerical × numerical, numerical × categorical, and categorical × categorical interactions, you’ve learned to capture the complex relationships that exist in real-world data.
The three interaction types each serve different purposes: numerical interactions reveal how effects change continuously, numerical × categorical interactions show how group membership modifies relationships, and categorical interactions identify special combination effects.
These fundamental skills in manual interaction creation prepare you for more advanced techniques like automated interaction detection and complex model building, while ensuring you maintain a clear understanding of what your models are actually capturing.
