0Pricing
Machine Learning Academy · บทเรียน

การสร้างคุณลักษณะใหม่: การแปลงลอการิทึม การจัดกลุ่มช่วง และปฏิสัมพันธ์

ผู้เรียนจะใช้การแปลงลอการิทึมกับคอลัมน์ที่มีการกระจายเบ้ จัดค่าต่อเนื่องเป็นหมวดหมู่แบบเรียงลำดับ และคูณคุณลักษณะเป็นคู่เพื่อจับผลของปฏิสัมพันธ์

การสร้างคุณลักษณะใหม่: การแปลงลอการิทึม การจัดกลุ่มช่วง และปฏิสัมพันธ์ เป็นบทเรียน Machine Learning Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Machine Learning Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Feature Engineering Matters

Feature engineering is the process of transforming raw data into representations that make patterns more accessible to machine learning models. Even the best algorithm is limited by the quality of its input features. Adding the right engineered feature can boost model accuracy more than any amount of hyperparameter tuning. The intuition: if you give the model the right numbers to work with, it can learn simpler, more generalisable rules than if it must discover complex transformations by itself.

Log Transforms: Taming Skewed Distributions

Many real-world quantities — income, house prices, population, transaction amounts — follow right-skewed distributions where most values are small but a few extreme values stretch the tail. Linear models and distance-based algorithms (KNN, SVM) perform poorly on such features because the large values dominate distance calculations. Applying np.log1p() (log of x+1, safe for zero values) compresses the scale, making the distribution more symmetric and reducing the influence of extreme outliers.

import numpy as np
import pandas as pd
from sklearn.datasets import fetch_california_housing

data = fetch_california_housing()
df = pd.DataFrame(data.data, columns=data.feature_names)

print('Population skewness (raw):', round(df['Population'].skew(), 2))
df['Population_log'] = np.log1p(df['Population'])
print('Population skewness (log): ', round(df['Population_log'].skew(), 2))

print('AveRooms skewness (raw):', round(df['AveRooms'].skew(), 2))
df['AveRooms_log'] = np.log1p(df['AveRooms'])
print('AveRooms skewness (log): ', round(df['AveRooms_log'].skew(), 2))

Log Transform and Model Performance

The benefit of log-transforming skewed features is not just visual — it directly improves model performance for algorithms that assume normally-distributed features (linear/logistic regression) or that use distances (KNN, SVM). For tree-based models (decision trees, random forests, gradient boosting), the benefit is smaller because trees split on thresholds and are naturally scale-invariant. Always verify the improvement with cross-validation rather than assuming the transform helps.

import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.datasets import fetch_california_housing
import pandas as pd

data = fetch_california_housing()
X, y = pd.DataFrame(data.data, columns=data.feature_names), data.target
X_log = X.copy()
for col in ['Population', 'AveRooms', 'AveBedrms', 'AveOccup']:
    X_log[col] = np.log1p(X_log[col])

for name, Xdata in [('Raw', X), ('Log-transformed', X_log)]:
    rmse = np.sqrt(-cross_val_score(Ridge(), Xdata, y, scoring='neg_mean_squared_error', cv=5).mean())
    print(f'{name} Ridge RMSE: {round(rmse, 4)}')

Binning: Discretising Continuous Features

Binning (or bucketing) converts a continuous feature into discrete categories. For example, age [0-100] might be binned into [child, teen, adult, senior]. This can help when the relationship between a feature and the target is non-linear in a step-function way — the model learns one coefficient per bin rather than trying to fit a linear slope. Pandas pd.cut() uses equal-width bins; pd.qcut() uses equal-frequency (quantile) bins that put the same number of examples in each bin.

import pandas as pd
import numpy as np

ages = pd.Series([5, 12, 18, 25, 45, 62, 80, 90])

# Equal-width bins
equal_bins = pd.cut(ages, bins=[0, 12, 18, 35, 60, 100],
                     labels=['child', 'teen', 'young_adult', 'adult', 'senior'])
print('Equal-width bins:', equal_bins.values)

# Quantile bins
quantile_bins = pd.qcut(ages, q=4, labels=['Q1', 'Q2', 'Q3', 'Q4'])
print('Quantile bins:', quantile_bins.values)

KBinsDiscretizer: Sklearn Binning for Pipelines

For use in scikit-learn Pipelines, KBinsDiscretizer provides the same functionality with the standard fit/transform API. The strategy parameter controls bin edges: 'uniform' (equal width), 'quantile' (equal frequency), or 'kmeans' (k-means clustering on the feature). The encode parameter controls output format: 'onehot' (one-hot sparse matrix), 'onehot-dense', or 'ordinal' (integer labels).

from sklearn.preprocessing import KBinsDiscretizer
import numpy as np

X = np.array([[15], [25], [35], [45], [55], [65], [75]])
kbd = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='quantile')
print('Original ages:', X.flatten())
print('Bin labels:  ', kbd.fit_transform(X).flatten())
print('Bin edges:   ', kbd.bin_edges_[0])

Interaction Features: Capturing Combinations

Interaction features are products or ratios of existing features that capture effects that neither feature alone can express. For example, rooms_per_person = total_rooms / population captures housing density better than either feature individually. A linear model cannot discover that room count × house age matters; you must create that product explicitly. Domain knowledge is invaluable here — ask 'what combination of these numbers would a domain expert find meaningful?'

import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
import numpy as np

data = fetch_california_housing()
df = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target

# Add meaningful interaction features
df['rooms_per_person'] = df['AveRooms'] / df['AveOccup'].clip(lower=0.1)
df['beds_per_room'] = df['AveBedrms'] / df['AveRooms'].clip(lower=0.1)

base_rmse = np.sqrt(-cross_val_score(make_pipeline(StandardScaler(), Ridge()), df[data.feature_names], y, cv=5, scoring='neg_mean_squared_error').mean())
enriched_rmse = np.sqrt(-cross_val_score(make_pipeline(StandardScaler(), Ridge()), df, y, cv=5, scoring='neg_mean_squared_error').mean())
print('Base RMSE:', round(base_rmse, 4))
print('Enriched RMSE:', round(enriched_rmse, 4))

Polynomial Features: Automated Interactions

PolynomialFeatures from scikit-learn automates interaction and polynomial term generation. With degree=2, it creates all pairwise products and squared terms. For p original features, it generates p(p+1)/2 interaction features plus p squared features. This is powerful for linear models on low-dimensional data, but becomes computationally prohibitive for high-dimensional data (100 features → 5,050 interaction terms). Always follow with feature selection or regularisation when using polynomial features.

from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import Ridge
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import numpy as np

X, y = fetch_california_housing(return_X_y=True)
for degree in [1, 2]:
    model = make_pipeline(StandardScaler(), PolynomialFeatures(degree=degree, include_bias=False), Ridge())
    rmse = np.sqrt(-cross_val_score(model, X, y, scoring='neg_mean_squared_error', cv=5).mean())
    print(f'Degree {degree}: RMSE={round(rmse, 4)}, n_features={PolynomialFeatures(degree).fit_transform(X[:1]).shape[1]}')

Ratio Features: Normalising for Scale

Ratio features normalise raw counts by a relevant denominator, removing scale effects. Examples: crime_rate = crimes / population, revenue_per_user = revenue / active_users, defect_rate = defects / total_units. Ratios are informative when the numerator and denominator vary independently and the ratio captures a meaningful rate that neither alone captures. Always guard against division by zero using .clip(lower=epsilon) or adding a small constant.

Target Encoding: When to Be Careful

For high-cardinality categorical features (hundreds of unique values), one-hot encoding creates too many dimensions. Target encoding replaces each category with the mean of the target for that category. For example, the 'city' feature gets replaced by the average sale price in each city. This is powerful but prone to leakage if done naively — the target encoding must be computed on the training data only and applied to the test fold. Use TargetEncoder from scikit-learn inside a Pipeline for correct implementation.

Evaluating Feature Engineering Impact

The right way to evaluate whether a new feature helps: (1) start with a baseline CV score on the original features; (2) add the new feature inside the training pipeline; (3) compare CV scores. Improvements of >0.5% on a robust metric (5-fold CV AUC or RMSE) are worth keeping. Features that hurt or show no improvement should be dropped — irrelevant features add noise and slow down training. Use feature importance (from tree models) or permutation importance to identify which engineered features are actually used.

Domain Knowledge vs Automated Engineering

Feature engineering can be done manually (using domain knowledge to craft specific features) or automatically (using tools like featuretools for deep feature synthesis or scikit-learn's PolynomialFeatures). Manual, domain-guided features typically outperform automated approaches because they embed human understanding of what the data actually means. Automated tools explore a much larger feature space and may find unexpected interactions, but also generate many useless features that require selection. The best practice is to start with domain-guided features, then optionally add automated candidates and filter them with feature selection.

Quick Check

Test your understanding of Feature Engineering from this lesson.

Lesson Recap

In this lesson you learned: log transforms reduce skew and make linear models work better on exponentially-distributed features, binning discretises continuous features into categories that capture step-wise relationships, and interaction features capture multiplicative effects that neither feature alone can express. Next up we explore extracting features from date and time columns.

คำถามที่พบบ่อย

บทเรียน “การสร้างคุณลักษณะใหม่: การแปลงลอการิทึม การจัดกลุ่มช่วง และปฏิสัมพันธ์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสร้างคุณลักษณะใหม่: การแปลงลอการิทึม การจัดกลุ่มช่วง และปฏิสัมพันธ์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Machine Learning Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสร้างคุณลักษณะใหม่: การแปลงลอการิทึม การจัดกลุ่มช่วง และปฏิสัมพันธ์”

ผู้เรียนจะใช้การแปลงลอการิทึมกับคอลัมน์ที่มีการกระจายเบ้ จัดค่าต่อเนื่องเป็นหมวดหมู่แบบเรียงลำดับ และคูณคุณลักษณะเป็นคู่เพื่อจับผลของปฏิสัมพันธ์ คุณปฏิบัติ Machine Learning Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Machine Learning Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Machine Learning Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “การสร้างคุณลักษณะใหม่: การแปลงลอการิทึม การจัดกลุ่มช่วง และปฏิสัมพันธ์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Machine Learning Academy นี้ได้ไหม

ได้ บทเรียน Machine Learning Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การสร้างคุณลักษณะใหม่: การแปลงลอการิทึม การจัดกลุ่มช่วง และปฏิสัมพันธ์
  2. การสกัดคุณลักษณะจากวันที่และเวลา
  3. การคัดเลือกคุณลักษณะ: เกณฑ์ความแปรปรวนและ SelectKBest
  4. การตัดคุณลักษณะแบบวนซ้ำด้วยการตรวจสอบไขว้
← กลับไปที่ Machine Learning Academy