Skip to main content

Lesson 1 of 9

Domain-Driven Feature Engineering: Ratios, Differences & Cyclical Encoding

Feature engineering transforms raw observations into explicit mathematical signals that align with problem domain mechanics. Andrew Ng famously stated: 'Applied machine learning is basically feature engineering'. Domain transformations include Ratios (e.g. Debt-to-Income, Click-Through-Rate), Differences (velocity changes relative to baselines), and Cyclical Trigonometric Encodings that preserve periodic circular continuity (hours of the day, days of the week, months).

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Cyclical Trigonometric Transformations & Domain Ratios

Cyclical Trigonometric Transformations & Domain Ratios
import pandas as pd
import numpy as np

# Synthetic e-commerce transaction dataset
np.random.seed(42)
n = 1000
df_events = pd.DataFrame({
    'timestamp': pd.date_range('2026-01-01', periods=n, freq='23min'),
    'user_total_spend': np.random.lognormal(5.0, 1.0, n),
    'user_order_count': np.random.poisson(4, n) + 1,
    'account_age_days': np.random.randint(1, 730, n)
})

# 1. CYCLICAL TRIGONOMETRIC ENCODINGS FOR PERIODIC FEATURES
# Problem: Hour 23 and Hour 0 are 1 hour apart, but numerically |23 - 0| = 23!
# Solution: Map onto unit circle using sine and cosine projections
hours = df_events['timestamp'].dt.hour
day_of_week = df_events['timestamp'].dt.dayofweek

df_events['sin_hour'] = np.sin(2 * np.pi * hours / 24.0)
df_events['cos_hour'] = np.cos(2 * np.pi * hours / 24.0)
df_events['sin_dow'] = np.sin(2 * np.pi * day_of_week / 7.0)
df_events['cos_dow'] = np.cos(2 * np.pi * day_of_week / 7.0)

# Euclidean distance between 23:00 and 00:00 is now identical to 01:00 and 02:00:
p_23 = np.array([np.sin(2*np.pi*23/24), np.cos(2*np.pi*23/24)])
p_00 = np.array([np.sin(2*np.pi*0/24), np.cos(2*np.pi*0/24)])
p_01 = np.array([np.sin(2*np.pi*1/24), np.cos(2*np.pi*1/24)])
print("=== CYCLICAL TEMPORAL CONTINUITY PROOF ===")
print(f"Distance between 23:00 and 00:00: {np.linalg.norm(p_23 - p_00):.4f}")
print(f"Distance between 00:00 and 01:00: {np.linalg.norm(p_00 - p_01):.4f} (Perfect equality!)")

# 2. DOMAIN INTERACTION RATIOS
df_events['avg_order_value'] = df_events['user_total_spend'] / df_events['user_order_count']
df_events['purchase_velocity'] = df_events['user_order_count'] / np.maximum(df_events['account_age_days'], 1.0)

print("\nSample Engineered Domain Features:")
print(df_events[['timestamp', 'sin_hour', 'cos_hour', 'avg_order_value', 'purchase_velocity']].head(3).to_string())

Pro Tip: Why Both Sine AND Cosine Are Required

You must include BOTH `sin` and `cos` components when encoding cyclical variables. If you only provide `sin(2*pi*hour/24)`, hour 3 (3:00 AM) and hour 9 (9:00 AM) produce identical sine values `sin(pi/4) = 0.7071`. The cosine component resolves this direction ambiguity.

Diagram
Loading diagramโ€ฆ

Feature engineering = 80% of ML success.

Hands-On Challenge: Build a Robust Ratio Transformer

Write a Scikit-Learn custom transformer `SafeRatioFeature(col_numerator, col_denominator, epsilon=1e-5)` that computes `numerator / (denominator + epsilon)` and automatically handles division-by-zero without producing `inf` or `NaN`.

Quick Quiz & Key Concept Checks

Common Pitfall: Engineering Features from Untrusted Client Clocks

Features derived from client device timestamps (e.g. phone system clock) can be manipulated by users or distorted by incorrect timezone settings. Always compute temporal features using authoritative, synchronized UTC server timestamps.

Finished this lesson?

0 of 9 in Module 10
Sign in to save progress

Topics in This Module

0/9 done