Перейти к содержимому
BIASED
К теме

По желанию

Регуляризация: сжатие и выбор штрафа

Проверить ридж и мягкое пороговое отсечение; воспроизвести выбор штрафа на синтетических данных с предобработкой внутри фолдов.

Версия
v2
Минут
~25
Проверка
Самопроверка в ноутбуке

Пока нет автопроверки на платформе: сравните вывод ячеек с ожидаемыми числами в ноутбуке. Это не долг и не влияет на процент освоения.

Скачать .ipynb

Скачайте ноутбук и запустите его локально. Требования к окружению указаны внутри.

Содержимое ноутбука

Можно прочитать с телефона. Код ниже не выполнялся в браузере; для запуска скачайте ноутбук.

Регуляризация: сжатие и выбор штрафа / Regularization: shrinkage and penalty selection

Activity version: 2. Optional desktop practice; no effect on mastery or certificates. / Необязательная практика за компьютером; не влияет на освоение и сертификаты.

Сравните ридж с МНК, проверьте мягкое пороговое отсечение и воспроизведите выбор штрафа внутри фолдов. / Compare ridge with least squares, check soft thresholding, and reproduce fold-local penalty selection.

The sensor fixture has 240 synthetic rows and eight inputs. Seed 20261113 fixes its independent normal draws, redundant pair and irrelevant auxiliaries. It contains no patient, user, scraped or equipment observations. The other hand-sized and simulated constructions are explicitly specified in the reviewed note. / В примере 240 синтетических строк и восемь входов. Seed 20261113 фиксирует независимые нормальные величины, избыточную пару и бесполезные признаки. Наблюдений за пациентами, пользователями или оборудованием и собранных постов нет. Другие небольшие и симуляционные примеры явно заданы в проверенном конспекте.

Run cells from top to bottom in a Python environment with NumPy, SciPy and scikit-learn. The code downloads no dataset or model and makes no network requests. Tested versions: python 3.14.7, numpy 2.5.4, scipy 1.18.1, scikit-learn 1.9.1. Other numerical backends may differ in final digits. / Запускайте ячейки сверху вниз в Python с NumPy, SciPy и scikit-learn. Код не загружает данные или модели и не делает сетевых запросов. Последние цифры могут отличаться между численными backend.

Provenance / Происхождение

Prepared for the Fedor Pakhurov project with Codex assistance. The main code cell is the project's reviewed example code from the published source note, revision 67f4698fb061d93879984860f99d5181e426221b. New self-checks and bilingual framing adapt that first-party material. The complete upstream review records its scientific references and material boundaries. The note bibliography supplies primary algorithm attribution; no external dataset, model weights, source figure or third-party notebook is included. The primary references are citations, not blanket reuse permission. AI assistance does not imply guaranteed exclusive copyright. No new redistribution license is granted here.

Подготовлено для проекта Фёдора Пахурова с помощью Codex. Основная ячейка содержит проверенный код примеров проекта из опубликованного конспекта; новые самопроверки и двуязычное сопровождение адаптируют этот материал. Ссылки выше фиксируют точную ревизию, обзор происхождения и первичные источники алгоритмов. Внешних датасетов, весов моделей, чужих рисунков и ноутбуков в файле нет. Новая лицензия на распространение не устанавливается.

import numpy as np, warnings
from sklearn.linear_model import Ridge, Lasso, ElasticNet, LinearRegression, lasso_path
from sklearn.model_selection import KFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
warnings.filterwarnings('ignore', category=FutureWarning)   # only scikit-learn 1.9's notice about n_alphas; convergence warnings stay on
rng = np.random.default_rng(0)
ridge = lambda X, y, lam: np.linalg.solve(X.T @ X + lam * np.eye(X.shape[1]), X.T @ y)
 
# worked example: x = (-1, 0, 1), centred y = (-2, 0, 2); then the same feature twice
x = np.array([[-1.], [0], [1]]); y = np.array([-2., 0, 2])
print(ridge(x, y, 1e-12), ridge(x, y, 2.0), ridge(np.hstack([x, x]), y, 2.0).round(3))   # [2.] [1.] [0.667 0.667]
 
# orthonormal features: the lasso soft-thresholds z = X^T y at lambda/2, ridge divides it by 1 + lambda
n = 50
Xo = np.linalg.qr(rng.normal(size=(n, 3)))[0]            # orthonormal columns
z = np.array([3.0, 1.0, -0.5]); yo = Xo @ z
lam = 2.0                                                # objective |y - Xw|^2 + lam |w|_1; scikit-learn's alpha = lam / (2n)
print(Lasso(alpha=lam / (2 * n), fit_intercept=False, tol=1e-12).fit(Xo, yo).coef_.round(3) + 0, ridge(Xo, yo, lam).round(3))
# [2. 0. 0.] [ 1.     0.333 -0.167]
 
# two nearly identical features (the least-squares note's example): ridge with lambda = 1 is stable
x1 = rng.normal(size=100); X2 = np.column_stack([x1, x1 + 0.01 * rng.normal(size=100)])
for _ in range(3):
    t = X2.sum(1) + rng.normal(size=100)
    print(np.linalg.lstsq(X2, t, rcond=None)[0].round(2), ridge(X2, t, 1.0).round(2))
# [ 4.81 -2.86] [0.99 0.95] | [-15.84  17.95] [0.97 1.13] | [-0.11  2.09] [0.98 0.99]
 
# New synthetic fixture; standardize and center for the full-data path only.
def make_data():
    # Independent dimensionless simulated inputs, with one deliberately redundant pair.
    rng = np.random.default_rng(20261113)
    base = rng.normal(size=(240, 8))
    X = base.copy()
    X[:, 1] = base[:, 0] + 0.08 * base[:, 1]
    y = 20 + X @ np.array([4., 4., -3., 2., 0., 0., 0., 0.])
    y += 4 * rng.normal(size=len(X))
    return X, y
 
X, yd = make_data()
names = ['sensor_a', 'sensor_b', 'control', 'ambient', 'aux_1', 'aux_2', 'aux_3', 'aux_4']
Xs = (X - X.mean(0)) / X.std(0); yc = yd - yd.mean()
assert np.max(abs(ridge(Xs, yc, 10) - Ridge(alpha=10).fit(Xs, yc).coef_)) < 1e-9
d2 = np.linalg.eigvalsh(Xs.T @ Xs)[::-1]
print(d2.round(3))
for lam in (1, 10, 100, 1000):
    factors = d2 / (d2 + lam)
    print(lam, factors[[0, -1]].round(3), round(factors.sum(), 2))
# lambda=10: [0.980, 0.079], df=6.81; lambda=100: df=5.04; lambda=1000: df=1.48
print(round(2 * abs(Xs.T @ yc).max(), 2), names[abs(Xs.T @ yc).argmax()])  # 3890.52 sensor_a
alphas, coefs, _ = lasso_path(Xs, yc, n_alphas=2000, eps=1e-5, max_iter=200000, tol=1e-9)
order = []
for column in coefs.T:
    order += [names[j] for j in np.flatnonzero(abs(column) > 1e-9) if names[j] not in order]
print(order)
# ['sensor_a', 'control', 'ambient', 'aux_1', 'sensor_b', 'aux_3', 'aux_2', 'aux_4']
 
# Selection scores, with every transformation inside each training fold.
cv = KFold(5, shuffle=True, random_state=17)
for deg in (1, 2, 3):
    pipe = lambda model: make_pipeline(PolynomialFeatures(deg, include_bias=False), StandardScaler(), model)
    score = lambda model: float(cross_val_score(pipe(model), X, yd, cv=cv, scoring='r2').mean())
    p = PolynomialFeatures(deg, include_bias=False).fit(X).n_output_features_
    r = {a: score(Ridge(alpha=a)) for a in (0.1, 1, 10, 100, 1000)}
    l = {a: score(Lasso(alpha=a, max_iter=200000, tol=1e-6)) for a in (0.03, 0.1, 0.3, 1, 3)}
    print(deg, p, round(score(LinearRegression()), 3), max(r, key=r.get), round(max(r.values()), 3), max(l, key=l.get), round(max(l.values()), 3))
# 1 8 0.812 1 0.812 0.1 0.814 | 2 44 0.770 10 0.787 0.3 0.809 | 3 164 -7.090 100 0.652 0.3 0.803
 
# two copies of one signal (correlation 0.999) and a useless feature, three draws: the lasso picks a copy, the elastic net shares
for seed in (0, 1, 2):
    r = np.random.default_rng(seed); zz = r.normal(size=200)
    Xe = np.column_stack([zz + 0.03 * r.normal(size=200), zz + 0.03 * r.normal(size=200), r.normal(size=200)])
    Xe = (Xe - Xe.mean(0)) / Xe.std(0); ye = 2 * zz + r.normal(size=200); ye -= ye.mean()
    print(Lasso(alpha=0.5).fit(Xe, ye).coef_.round(2) + 0, ElasticNet(alpha=0.5, l1_ratio=0.5).fit(Xe, ye).coef_.round(2) + 0)
# [1.46 0.   0.  ] [0.76 0.76 0.  ] | [0.  1.4 0. ] [0.72 0.74 0.  ] | [0.6  0.76 0.  ] [0.71 0.72 0.  ]
 

Self-check / Самопроверка

The next cell verifies the lesson-specific claims. / Следующая ячейка проверяет утверждения урока.

# New BIASED self-checks on the independently specified sensor fixture.
check_X, check_y = make_data()
check_X = (check_X - check_X.mean(axis=0)) / check_X.std(axis=0)
check_y = check_y - check_y.mean()
eigenvalues = np.linalg.eigvalsh(check_X.T @ check_X)
factors = eigenvalues / (eigenvalues + 10)
assert np.isclose(factors.sum(), 6.810897499, atol=1e-6)
assert factors[0] < 0.08 and factors[-1] > 0.97
check_lasso = Lasso(alpha=0.1, max_iter=200000, tol=1e-6).fit(check_X, check_y)
selected = np.flatnonzero(abs(check_lasso.coef_) > 1e-8)
assert len(selected) == 7
assert sum(index >= 4 for index in selected) == 3
print(f"Ridge df at lambda=10: {factors.sum():.6f}")
print("Selected coefficients: 7; selected irrelevant auxiliaries: 3")
print("Self-checks passed; feature selection is not causal identification")
 

Try a change / Измените условие

Измените силу шума и заново запустите весь поиск. Сохраните предобработку внутри фолдов. Проверьте, совпадает ли выбор признаков с ненулевыми коэффициентами генератора. / Change noise strength and rerun the complete search. Keep preprocessing inside folds. Compare selected features with the nonzero generating coefficients.