Çoklu Doğrusal Regresyon ve Özellik Önem Derecesi
Modeli birden çok girdi özelliğini kapsayacak şekilde genişletin, her katsayıyı özellik önem derecesi olarak yorumlayın ve R-kare ile değerlendirin.
Çoklu Doğrusal Regresyon ve Özellik Önem Derecesi, CoddyKit'te ücretsiz bir Machine Learning Academy dersidir. Bu, 4 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Machine Learning Academy öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Machine Learning Academy kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
Beyond a Single Feature
Real prediction problems almost always have multiple relevant inputs. House price depends on square footage, number of bedrooms, location, age, and dozens of other factors. Multiple linear regression extends the single-feature line to use all available features simultaneously:
ŷ = w₁x₁ + w₂x₂ + ... + wₙxₙ + b
Each feature gets its own weight, and the model learns all weights simultaneously by minimising MSE. Adding more relevant features almost always improves prediction accuracy — as long as those features genuinely carry information about the target.
import pandas as pd
import numpy as np
# Multi-feature housing dataset
np.random.seed(42)
n = 300
df = pd.DataFrame({
'sqft': np.random.randint(600, 4000, n),
'bedrooms': np.random.randint(1, 7, n),
'bathrooms': np.random.randint(1, 5, n),
'age': np.random.randint(1, 60, n),
'distance_to_center': np.random.uniform(1, 30, n)
})
df['price'] = (150 * df['sqft'] + 8000 * df['bedrooms']
- 300 * df['age'] - 5000 * df['distance_to_center']
+ 40000 + np.random.normal(0, 20000, n))
print(df.head())Training with Multiple Features
The scikit-learn API is identical for one feature or one hundred features — you simply pass the full feature matrix. The model automatically fits one coefficient per column in X.
With multiple features, R² typically increases compared to the single-feature model, because each additional informative feature provides the model with more signal to work with. However, adding irrelevant or noisy features can actually hurt performance by introducing overfitting, especially on small datasets.
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
import pandas as pd
import numpy as np
# (df defined in previous scene)
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
X = df[features]
y = df['price']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(f'Multi-feature R2: {r2_score(y_test, y_pred):.3f}')Inspecting the Coefficients
After fitting a multi-feature model, model.coef_ is an array with one value per feature. Each value is the predicted change in y for a one-unit increase in that feature, assuming all other features are held constant.
For example, a coefficient of 150 for sqft means: controlling for bedrooms, age, and all other features, one additional square foot is predicted to add $150 to the price. This partial effect interpretation is what makes linear regression so useful for explaining which factors drive a prediction.
import pandas as pd
from sklearn.linear_model import LinearRegression
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
# Create a readable coefficient table
coef_df = pd.DataFrame({
'Feature': features,
'Coefficient': model.coef_
}).sort_values('Coefficient', ascending=False)
print(coef_df.to_string(index=False))
print(f'\nIntercept: {model.intercept_:,.0f}')Why Raw Coefficients Can Be Misleading
Raw coefficients are not directly comparable when features have different units and scales. In the housing model, sqft ranges from 600 to 4000 while bathrooms ranges from 1 to 5. A coefficient of 150 for sqft and 8000 for bedrooms does not mean bedrooms are 53x more important — it means a one-unit change in bedrooms (a huge change) has 53x the effect of a one-unit change in sqft (a tiny change).
To compare feature importance fairly, you must first standardise all features to the same scale (zero mean, unit variance). Then the coefficients reflect the effect of a one-standard-deviation change in each feature, which is comparable across features.
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
import pandas as pd
import numpy as np
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
# Scale features to zero mean, unit variance
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train[features])
model_scaled = LinearRegression()
model_scaled.fit(X_train_scaled, y_train)
# Now coefficients ARE comparable
coef_df = pd.DataFrame({
'Feature': features,
'Standardised Coefficient': model_scaled.coef_
}).sort_values('Standardised Coefficient', key=abs, ascending=False)
print(coef_df.to_string(index=False))Feature Importance Bar Chart
Visualising standardised coefficients as a bar chart gives stakeholders an intuitive view of which features drive the model's predictions. Positive bars push the prediction up; negative bars push it down. The longer the bar, the greater the impact of a one-standard-deviation change in that feature.
This plot is one of the most persuasive tools for communicating model behaviour to non-technical audiences. It answers 'what matters?' in a single, easy-to-read chart.
import matplotlib.pyplot as plt
import numpy as np
feature_names = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
coeffs = model_scaled.coef_
colors = ['steelblue' if c > 0 else 'salmon' for c in coeffs]
plt.figure(figsize=(8, 5))
plt.barh(feature_names, coeffs, color=colors)
plt.axvline(x=0, color='black', linewidth=0.8)
plt.xlabel('Standardised Coefficient (impact per 1 std dev)')
plt.title('Feature Importance from Linear Regression')
plt.tight_layout()
plt.show()R-Squared and Adjusted R-Squared
Regular R² always increases (or stays the same) when you add more features, even if those features are random noise. This makes it a misleading metric for model selection with different numbers of features.
Adjusted R² corrects for this by penalising for each additional feature: Adj R² = 1 - (1-R²)(n-1)/(n-p-1), where n is the number of samples and p is the number of features. If an added feature does not improve the model enough to justify its complexity, Adjusted R² decreases. Use Adjusted R² when comparing models with different numbers of features.
from sklearn.metrics import r2_score
import numpy as np
def adjusted_r2(y_true, y_pred, n_features):
r2 = r2_score(y_true, y_pred)
n = len(y_true)
adj = 1 - (1 - r2) * (n - 1) / (n - n_features - 1)
return adj
y_pred_test = model.predict(X_test[features])
r2 = r2_score(y_test, y_pred_test)
adj_r2 = adjusted_r2(y_test, y_pred_test, n_features=len(features))
print(f'R2: {r2:.4f}')
print(f'Adjusted R2: {adj_r2:.4f}') # slightly lower, penalises complexityMulticollinearity: Correlated Features
Multicollinearity occurs when two or more features are highly correlated with each other. For example, sqft and number_of_rooms often move together — bigger houses have more rooms. When features are highly correlated, the model cannot reliably estimate individual coefficients because it cannot distinguish which feature is actually responsible for the effect on y.
Symptoms include: coefficients that change dramatically when you add or remove a single feature, very large coefficient values with opposite signs, or high R² but all coefficients with large standard errors. The Variance Inflation Factor (VIF) is the standard diagnostic for multicollinearity.
import pandas as pd
import numpy as np
# Detect multicollinearity via correlation matrix
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
corr = df[features].corr()
print('Feature correlation matrix:')
print(corr.round(2))
# High correlation (>0.7) between two features indicates multicollinearity
high_corr = (corr.abs() > 0.7) & (corr != 1.0)
print('\nHighly correlated pairs:')
print(high_corr)Feature Selection: Adding and Removing Features
Not all features improve model performance. Adding irrelevant features increases complexity and can hurt generalisation. A disciplined approach to feature selection involves comparing models with different subsets of features using cross-validated Adjusted R².
Iterative forward selection adds one feature at a time, keeping it only if it improves the validation score. Recursive feature elimination (RFE) removes the least important feature iteratively. Scikit-learn provides both approaches.
from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
X_all = df[features].values
y_all = df['price'].values
# Keep the top 3 most informative features
rfe = RFE(estimator=LinearRegression(), n_features_to_select=3)
rfe.fit(X_all, y_all)
selected = [f for f, s in zip(features, rfe.support_) if s]
print('Selected features:', selected)Prediction on New Houses
Once you have a trained multi-feature model, making predictions on new data is straightforward: create a DataFrame or array with the same feature columns in the same order, and call model.predict(). The model returns one predicted price per row.
If you used a Pipeline with a scaler, pass the raw (unscaled) data — the pipeline automatically applies the same scaling transformation that was fitted on training data. This is another reason why Pipelines are the professional way to work.
import pandas as pd
import numpy as np
# New houses to value
new_houses = pd.DataFrame({
'sqft': [1200, 2500, 800],
'bedrooms': [3, 4, 2],
'bathrooms': [2, 3, 1],
'age': [10, 5, 30],
'distance_to_center': [5.0, 12.0, 2.5]
})
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
predictions = model.predict(new_houses[features])
for i, (_, row) in enumerate(new_houses.iterrows()):
print(f'House {i+1}: {row["sqft"]} sqft, {row["bedrooms"]}bd -> ${predictions[i]:,.0f}')Polynomial Features for Non-Linear Relationships
Linear regression is limited to linear relationships, but you can model non-linear patterns by engineering polynomial features. PolynomialFeatures in scikit-learn automatically creates squared, cubed, and interaction terms from your original features.
A degree-2 polynomial on two features x₁ and x₂ produces: x₁, x₂, x₁², x₂², x₁x₂. The model is still linear in its parameters (which is why it is still 'linear regression'), but it can fit curved relationships in the original feature space. Use with cross-validation to pick the optimal degree.
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import r2_score
import numpy as np
np.random.seed(0)
X = np.random.uniform(0, 5, 100).reshape(-1, 1)
y = X.ravel()**2 + np.random.randn(100) * 2 # quadratic true relationship
# Compare linear vs degree-2 polynomial
for degree in [1, 2, 3]:
pipe = Pipeline([('poly', PolynomialFeatures(degree=degree)),
('model', LinearRegression())])
pipe.fit(X, y)
r2 = r2_score(y, pipe.predict(X))
print(f'Degree {degree} R2 (train): {r2:.3f}')Summary: Coefficients as Feature Importance
Key takeaways for using coefficients to measure feature importance:
- Raw coefficients depend on feature scale — a coefficient of 150 for sqft is not directly comparable to 8000 for bedrooms unless both are standardised.
- Standardised coefficients (from a model trained on scaled features) measure the effect of a one-standard-deviation change in each feature, making them directly comparable.
- Large absolute values indicate influential features; small values (near zero) indicate weak or redundant features.
- Always confirm that high-importance features have a causal or meaningful relationship with the target, not just statistical correlation in the training data.
Quick Check
Test your understanding of Machine Learning with Python concepts from this lesson.
Lesson Recap
In this lesson you learned: multiple linear regression assigns one weight per feature in the equation ŷ = w₁x₁ + ... + wₙxₙ + b, raw coefficients must be standardised before comparing importance across features with different scales, and Adjusted R² penalises added features to prevent overfitting during model selection. Next up we cross the boundary from predicting numbers to predicting categories with logistic regression and threshold-based classification.
Sıkça Sorulan Sorular
“Çoklu Doğrusal Regresyon ve Özellik Önem Derecesi” dersi ücretsiz mi?
Evet — “Çoklu Doğrusal Regresyon ve Özellik Önem Derecesi” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Machine Learning Academy kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Machine Learning Academy kursu toplamda 4 dersten oluşur.
“Çoklu Doğrusal Regresyon ve Özellik Önem Derecesi” dersinde ne öğreneceğim?
Modeli birden çok girdi özelliğini kapsayacak şekilde genişletin, her katsayıyı özellik önem derecesi olarak yorumlayın ve R-kare ile değerlendirin. Machine Learning Academy ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
Machine Learning Academy öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te Machine Learning Academy, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 4. dersidir.
“Çoklu Doğrusal Regresyon ve Özellik Önem Derecesi” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu Machine Learning Academy dersinde kod yazıp çalıştırabilir miyim?
Evet. Her Machine Learning Academy dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- Bir Doğrunun Denklemi: Eğim, Kesişim ve Tahminler
- Maliyet Fonksiyonları ve En Küçük Kareler
- scikit-learn ile Doğrusal Regresyon Eğitme
- Çoklu Doğrusal Regresyon ve Özellik Önem Derecesi