<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[advancedregression]]></title><description><![CDATA[advancedregression]]></description><link>https://advancedregression.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 25 Sep 2026 04:24:00 GMT</lastBuildDate><atom:link href="https://advancedregression.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[My Week 15 Regression Journey: From Confusion to Clarity]]></title><description><![CDATA[How I struggled, debugged, and finally mastered Polynomial, SVR, and Decision Tree Regression

📌 Introduction
Welcome to my Week 15 learning journey in Advanced Regression Techniques! As part of my machine learning specialization, this week was all ...]]></description><link>https://advancedregression.hashnode.dev/my-week-15-regression-journey-from-confusion-to-clarity</link><guid isPermaLink="true">https://advancedregression.hashnode.dev/my-week-15-regression-journey-from-confusion-to-clarity</guid><dc:creator><![CDATA[Sravs]]></dc:creator><pubDate>Tue, 20 Jan 2026 22:36:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1768948542717/5e28b347-06dc-4995-b4d2-987182677354.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>How I struggled, debugged, and finally mastered Polynomial, SVR, and Decision Tree Regression</em></p>
<hr />
<h2 id="heading-introduction">📌 Introduction</h2>
<p>Welcome to my Week 15 learning journey in <strong>Advanced Regression Techniques</strong>! As part of my machine learning specialization, this week was all about moving beyond simple linear regression into the wild world of <strong>Polynomial Regression, Support Vector Regression (SVR), and Decision Tree Regression</strong>.</p>
<p>I’ll be honest—I started this week overwhelmed. Terms like <em>kernel tricks</em>, <em>feature scaling</em>, and <em>tree pruning</em> sounded like jargon from a sci-fi movie. But by the end, I not only built models—I understood <em>why</em> they worked, <em>when</em> to use them, and <strong>how to debug them</strong>.</p>
<p>Here’s my story, complete with code snippets, errors, fixes, and key learnings. You can follow along with my <a target="_blank" href="https://colab.research.google.com/drive/1s1cQrWhyhSQXw4cIIIlPG_jnlJCzlGRc?usp=sharing"><strong>Google Colab notebook here</strong></a>.</p>
<hr />
<h2 id="heading-the-datasets">📁 The Datasets</h2>
<p>We were given a neatly organized folder (as per the Data Dictionary) with:</p>
<ul>
<li><p><strong>Task Datasets</strong> (for practice)</p>
</li>
<li><p><strong>Assignment Datasets</strong> (for comparison)</p>
</li>
<li><p><strong>Assessment Dataset</strong> (final project)</p>
</li>
</ul>
<p>Each dataset was specifically designed to highlight the strengths and weaknesses of different regression techniques.</p>
<hr />
<h2 id="heading-task-1-polynomial-regression">🧪 Task 1: Polynomial Regression</h2>
<h3 id="heading-the-goal">The Goal</h3>
<p>Compare <strong>Linear Regression</strong> vs <strong>Polynomial Regression</strong> on <code>task1_polynomial_data.csv</code>.</p>
<h3 id="heading-the-struggle">The Struggle</h3>
<p>I started by fitting a simple linear model. The results were… okay. But when I plotted it, I immediately saw the problem:</p>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
<span class="hljs-keyword">from</span> sklearn.linear_model <span class="hljs-keyword">import</span> LinearRegression

<span class="hljs-comment"># Load data</span>
data = pd.read_csv(<span class="hljs-string">'task1_polynomial_data.csv'</span>)
X = data[[<span class="hljs-string">'Experience_Years'</span>]].values
y = data[<span class="hljs-string">'Salary'</span>].values

<span class="hljs-comment"># Linear regression</span>
lin_reg = LinearRegression()
lin_reg.fit(X, y)

<span class="hljs-comment"># Plot</span>
plt.scatter(X, y, color=<span class="hljs-string">'blue'</span>, label=<span class="hljs-string">'Actual'</span>)
plt.plot(X, lin_reg.predict(X), color=<span class="hljs-string">'red'</span>, linewidth=<span class="hljs-number">2</span>, label=<span class="hljs-string">'Linear Fit'</span>)
plt.title(<span class="hljs-string">"Linear Regression on Non-Linear Data"</span>)
plt.xlabel(<span class="hljs-string">'Experience Years'</span>)
plt.ylabel(<span class="hljs-string">'Salary'</span>)
plt.legend()
plt.show()
</code></pre>
<p>The line was too rigid. Clearly, the relationship wasn't linear. My R² score was only 0.72—not terrible, but not great.</p>
<h3 id="heading-the-fix">The Fix</h3>
<p>I used <code>PolynomialFeatures</code> from sklearn to transform the features:</p>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.preprocessing <span class="hljs-keyword">import</span> PolynomialFeatures
<span class="hljs-keyword">from</span> sklearn.metrics <span class="hljs-keyword">import</span> mean_squared_error, r2_score

<span class="hljs-comment"># Try different degrees</span>
degrees = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
results = []

<span class="hljs-keyword">for</span> degree <span class="hljs-keyword">in</span> degrees:
    poly = PolynomialFeatures(degree=degree)
    X_poly = poly.fit_transform(X)

    poly_reg = LinearRegression()
    poly_reg.fit(X_poly, y)

    y_pred = poly_reg.predict(X_poly)
    mse = mean_squared_error(y, y_pred)
    r2 = r2_score(y, y_pred)

    results.append((degree, mse, r2))

    print(<span class="hljs-string">f"Degree <span class="hljs-subst">{degree}</span>: MSE = <span class="hljs-subst">{mse:<span class="hljs-number">.2</span>f}</span>, R² = <span class="hljs-subst">{r2:<span class="hljs-number">.4</span>f}</span>"</span>)
</code></pre>
<h3 id="heading-the-error-i-made">⚠️ The Error I Made</h3>
<p>I initially tried degree=6 without cross-validation and got <strong>perfect training fit</strong> but realized I was overfitting. The model was memorizing noise!</p>
<h3 id="heading-key-learning">Key Learning</h3>
<ul>
<li><p><strong>Degree matters</strong>: Too low → underfitting, too high → overfitting.</p>
</li>
<li><p><strong>Always visualize</strong> the fit against the actual data.</p>
</li>
<li><p><strong>Cross-validate polynomial degrees</strong> using <code>cross_val_score</code>.</p>
</li>
</ul>
<p><strong>Best result</strong>: Degree 3 gave the best balance (R² = 0.96).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768947062143/f1d8b01e-71eb-48e8-b0c8-f83c1053c28c.png" alt class="image--center mx-auto" /></p>
<hr />
<h2 id="heading-task-2-support-vector-regression-svr">🔥 Task 2: Support Vector Regression (SVR)</h2>
<h3 id="heading-the-goal-1">The Goal</h3>
<p>Predict ice cream sales from temperature using SVR with an RBF kernel on <code>task2_svr_data.csv</code>.</p>
<h3 id="heading-the-error-that-broke-me">The Error That Broke Me</h3>
<p>I forgot to <strong>scale the features</strong>. SVR is sensitive to scale! My model's predictions were completely off:</p>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.svm <span class="hljs-keyword">import</span> SVR

<span class="hljs-comment"># WRONG: Not scaling</span>
svr = SVR(kernel=<span class="hljs-string">'rbf'</span>)
svr.fit(X, y)  <span class="hljs-comment"># Disaster!</span>

<span class="hljs-comment"># Error message didn't show, but predictions were terrible</span>
<span class="hljs-comment"># MSE was in the millions instead of thousands</span>
</code></pre>
<h3 id="heading-the-fix-1">The Fix</h3>
<p>I added <code>StandardScaler</code>:</p>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.preprocessing <span class="hljs-keyword">import</span> StandardScaler
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np

<span class="hljs-comment"># Scale features</span>
sc_X = StandardScaler()
sc_y = StandardScaler()

X_scaled = sc_X.fit_transform(X)
y_scaled = sc_y.fit_transform(y.reshape(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>)).ravel()  <span class="hljs-comment"># Important: ravel()</span>

<span class="hljs-comment"># Now SVR works</span>
svr = SVR(kernel=<span class="hljs-string">'rbf'</span>, C=<span class="hljs-number">100</span>, gamma=<span class="hljs-number">0.1</span>)
svr.fit(X_scaled, y_scaled)

<span class="hljs-comment"># Don't forget to inverse transform predictions!</span>
y_pred_scaled = svr.predict(X_scaled)
y_pred = sc_y.inverse_transform(y_pred_scaled.reshape(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>))
</code></pre>
<h3 id="heading-another-gotcha">⚠️ Another Gotcha</h3>
<p>The <code>gamma</code> parameter! Too high → overfitting, too low → underfitting. I used GridSearchCV to find optimal values:</p>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> GridSearchCV

param_grid = {
    <span class="hljs-string">'C'</span>: [<span class="hljs-number">0.1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">100</span>],
    <span class="hljs-string">'gamma'</span>: [<span class="hljs-number">0.01</span>, <span class="hljs-number">0.1</span>, <span class="hljs-number">1</span>, <span class="hljs-string">'scale'</span>],
    <span class="hljs-string">'kernel'</span>: [<span class="hljs-string">'rbf'</span>, <span class="hljs-string">'linear'</span>]
}

grid = GridSearchCV(SVR(), param_grid, cv=<span class="hljs-number">5</span>, scoring=<span class="hljs-string">'r2'</span>)
grid.fit(X_scaled, y_scaled)
print(<span class="hljs-string">f"Best parameters: <span class="hljs-subst">{grid.best_params_}</span>"</span>)
</code></pre>
<h3 id="heading-key-learning-1">Key Learning</h3>
<ul>
<li><p><strong>Always scale features for SVR</strong> (and many other algorithms).</p>
</li>
<li><p>The <code>C</code> parameter controls tolerance for errors (regularization).</p>
</li>
<li><p><code>gamma</code> controls the influence of individual points.</p>
</li>
<li><p><strong>Inverse transform</strong> your predictions back to original scale.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768947269100/18b70932-7ea8-42f1-a26c-127e9f14c8b1.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768947241776/5baa4ce5-3382-41b7-8481-ca91743a7a42.png" alt class="image--center mx-auto" /></p>
<hr />
<h2 id="heading-task-3-decision-tree-regression">🌳 Task 3: Decision Tree Regression</h2>
<h3 id="heading-the-goal-2">The Goal</h3>
<p>Model study hours vs exam scores using a Decision Tree Regressor on <code>task3_decision_tree_data.csv</code>.</p>
<h3 id="heading-the-overfitting-trap">The "Overfitting" Trap</h3>
<p>My first tree was too deep. It memorized the training data:</p>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.tree <span class="hljs-keyword">import</span> DecisionTreeRegressor

<span class="hljs-comment"># WRONG: No depth limit</span>
tree_reg = DecisionTreeRegressor(random_state=<span class="hljs-number">42</span>)
tree_reg.fit(X, y)

<span class="hljs-comment"># Training score was perfect (R² = 1.0)</span>
<span class="hljs-comment"># But this was obviously overfitting</span>
</code></pre>
<h3 id="heading-the-visualization-that-saved-me">The Visualization That Saved Me</h3>
<p>I plotted the decision tree's predictions across a high-resolution range:</p>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-comment"># Create high-res X for smooth plot</span>
X_grid = np.arange(min(X), max(X), <span class="hljs-number">0.01</span>).reshape(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>)

plt.scatter(X, y, color=<span class="hljs-string">'red'</span>, label=<span class="hljs-string">'Actual'</span>)
plt.plot(X_grid, tree_reg.predict(X_grid), color=<span class="hljs-string">'blue'</span>, label=<span class="hljs-string">'Tree Prediction'</span>)
plt.title(<span class="hljs-string">"Decision Tree Regression (Overfitting)"</span>)
plt.xlabel(<span class="hljs-string">'Hours Studied'</span>)
plt.ylabel(<span class="hljs-string">'Exam Score'</span>)
plt.legend()
plt.show()
</code></pre>
<p>The plot showed a <strong>jagged, stair-step pattern</strong> that was clearly memorizing noise.</p>
<h3 id="heading-the-fix-2">The Fix</h3>
<p>I tuned <code>max_depth</code> and used <code>min_samples_split</code>:</p>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-comment"># Better: Regularized tree</span>
tree_reg = DecisionTreeRegressor(
    max_depth=<span class="hljs-number">3</span>,
    min_samples_split=<span class="hljs-number">5</span>,
    min_samples_leaf=<span class="hljs-number">2</span>,
    random_state=<span class="hljs-number">42</span>
)
tree_reg.fit(X, y)

<span class="hljs-comment"># Visualize tree structure (optional but helpful)</span>
<span class="hljs-keyword">from</span> sklearn.tree <span class="hljs-keyword">import</span> plot_tree
plt.figure(figsize=(<span class="hljs-number">12</span>, <span class="hljs-number">8</span>))
plot_tree(tree_reg, filled=<span class="hljs-literal">True</span>, feature_names=[<span class="hljs-string">'Hours_Studied'</span>])
plt.show()
</code></pre>
<h3 id="heading-key-learning-2">Key Learning</h3>
<ul>
<li><p>Trees can <strong>overfit</strong> easily if not regularized.</p>
</li>
<li><p>Visualize the tree with <code>plot_tree()</code> to understand splits.</p>
</li>
<li><p>Use <code>max_depth</code>, <code>min_samples_split</code>, and <code>min_samples_leaf</code> for regularization.</p>
</li>
<li><p>Decision trees <strong>don't need feature scaling</strong> (unlike SVR).</p>
</li>
</ul>
<hr />
<h2 id="heading-assignment-1-salary-prediction">📊 Assignment 1: Salary Prediction</h2>
<p>Here's where things got real. I had to compare <strong>all three techniques</strong> on <code>assignment1_salary_prediction.csv</code>.</p>
<h3 id="heading-my-comparison-script">My Comparison Script</h3>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> train_test_split
<span class="hljs-keyword">from</span> sklearn.preprocessing <span class="hljs-keyword">import</span> PolynomialFeatures, StandardScaler
<span class="hljs-keyword">from</span> sklearn.linear_model <span class="hljs-keyword">import</span> LinearRegression
<span class="hljs-keyword">from</span> sklearn.svm <span class="hljs-keyword">import</span> SVR
<span class="hljs-keyword">from</span> sklearn.tree <span class="hljs-keyword">import</span> DecisionTreeRegressor
<span class="hljs-keyword">from</span> sklearn.metrics <span class="hljs-keyword">import</span> mean_squared_error, r2_score

<span class="hljs-comment"># Load data</span>
data = pd.read_csv(<span class="hljs-string">'assignment1_salary_prediction.csv'</span>)
X = data[[<span class="hljs-string">'Position_Level'</span>]].values
y = data[<span class="hljs-string">'Salary'</span>].values

<span class="hljs-comment"># Split data</span>
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=<span class="hljs-number">0.2</span>, random_state=<span class="hljs-number">42</span>)

results = {}

<span class="hljs-comment"># 1. Linear Regression</span>
lr = LinearRegression()
lr.fit(X_train, y_train)
y_pred = lr.predict(X_test)
results[<span class="hljs-string">'Linear'</span>] = {
    <span class="hljs-string">'MSE'</span>: mean_squared_error(y_test, y_pred),
    <span class="hljs-string">'R2'</span>: r2_score(y_test, y_pred)
}

<span class="hljs-comment"># 2. Polynomial Regression (degree=6)</span>
poly = PolynomialFeatures(degree=<span class="hljs-number">6</span>)
X_poly_train = poly.fit_transform(X_train)
X_poly_test = poly.transform(X_test)

poly_reg = LinearRegression()
poly_reg.fit(X_poly_train, y_train)
y_pred = poly_reg.predict(X_poly_test)
results[<span class="hljs-string">'Polynomial (deg=6)'</span>] = {
    <span class="hljs-string">'MSE'</span>: mean_squared_error(y_test, y_pred),
    <span class="hljs-string">'R2'</span>: r2_score(y_test, y_pred)
}

<span class="hljs-comment"># 3. SVR</span>
scaler_X = StandardScaler()
scaler_y = StandardScaler()

X_train_scaled = scaler_X.fit_transform(X_train)
y_train_scaled = scaler_y.fit_transform(y_train.reshape(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>)).ravel()
X_test_scaled = scaler_X.transform(X_test)

svr = SVR(kernel=<span class="hljs-string">'rbf'</span>, C=<span class="hljs-number">100</span>, gamma=<span class="hljs-number">0.1</span>)
svr.fit(X_train_scaled, y_train_scaled)

y_pred_scaled = svr.predict(X_test_scaled)
y_pred = scaler_y.inverse_transform(y_pred_scaled.reshape(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>))
results[<span class="hljs-string">'SVR (RBF)'</span>] = {
    <span class="hljs-string">'MSE'</span>: mean_squared_error(y_test, y_pred),
    <span class="hljs-string">'R2'</span>: r2_score(y_test, y_pred)
}

<span class="hljs-comment"># 4. Decision Tree</span>
tree = DecisionTreeRegressor(max_depth=<span class="hljs-number">3</span>, random_state=<span class="hljs-number">42</span>)
tree.fit(X_train, y_train)
y_pred = tree.predict(X_test)
results[<span class="hljs-string">'Decision Tree'</span>] = {
    <span class="hljs-string">'MSE'</span>: mean_squared_error(y_test, y_pred),
    <span class="hljs-string">'R2'</span>: r2_score(y_test, y_pred)
}

<span class="hljs-comment"># Display results</span>
<span class="hljs-keyword">for</span> model, metrics <span class="hljs-keyword">in</span> results.items():
    print(<span class="hljs-string">f"<span class="hljs-subst">{model}</span>: MSE = <span class="hljs-subst">{metrics[<span class="hljs-string">'MSE'</span>]:<span class="hljs-number">.2</span>f}</span>, R² = <span class="hljs-subst">{metrics[<span class="hljs-string">'R2'</span>]:<span class="hljs-number">.4</span>f}</span>"</span>)
</code></pre>
<h3 id="heading-my-comparison-results">My Comparison Results</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Model</td><td>MSE</td><td>R² Score</td></tr>
</thead>
<tbody>
<tr>
<td>Linear Regression</td><td>4,200,000,000</td><td>0.72</td></tr>
<tr>
<td>Polynomial (degree=6)</td><td>1,100,000,000</td><td>0.93</td></tr>
<tr>
<td>SVR (RBF)</td><td>1,400,000,000</td><td>0.91</td></tr>
<tr>
<td>Decision Tree</td><td>1,300,000,000</td><td>0.92</td></tr>
</tbody>
</table>
</div><p><strong>Winner</strong>: Polynomial Regression (degree=3).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768947834303/416ffdce-7c05-4c51-a9e7-5d13af7ce136.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-reflection">Reflection</h3>
<ul>
<li><p>Polynomial regression excelled because the salary trend was <strong>exponential</strong>.</p>
</li>
<li><p>SVR was close but needed careful tuning of C and gamma.</p>
</li>
<li><p>Decision trees were interpretable but slightly less accurate.</p>
</li>
<li><p><strong>Important</strong>: I learned to always split data before comparing models!</p>
</li>
</ul>
<hr />
<h2 id="heading-assignment-2-multi-feature-regression">🧩 Assignment 2: Multi-Feature Regression</h2>
<p>Now with <strong>4 features</strong> in <code>assignment2_energy_efficiency.csv</code>, I practiced feature importance and hyperparameter tuning.</p>
<h3 id="heading-key-code-snippet-feature-importance">Key Code Snippet: Feature Importance</h3>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-comment"># Train decision tree</span>
tree = DecisionTreeRegressor(max_depth=<span class="hljs-number">5</span>, random_state=<span class="hljs-number">42</span>)
tree.fit(X_train, y_train)

<span class="hljs-comment"># Get feature importance</span>
importance = tree.feature_importances_
features = [<span class="hljs-string">'Temperature'</span>, <span class="hljs-string">'Humidity'</span>, <span class="hljs-string">'Wind_Speed'</span>, <span class="hljs-string">'Solar_Radiation'</span>]

<span class="hljs-keyword">for</span> feature, imp <span class="hljs-keyword">in</span> zip(features, importance):
    print(<span class="hljs-string">f"<span class="hljs-subst">{feature}</span>: <span class="hljs-subst">{imp:<span class="hljs-number">.4</span>f}</span>"</span>)
</code></pre>
<h3 id="heading-the-mistake">⚠️ The Mistake</h3>
<p>I initially trained SVR without tuning on the multi-feature data and got poor results. Lesson: <strong>GridSearchCV is essential for SVR with multiple features</strong>.</p>
<h3 id="heading-key-takeaway">Key Takeaway</h3>
<p>For multi-feature non-linear problems:</p>
<ul>
<li><p><strong>SVR</strong> with scaling + RBF kernel + GridSearch works well.</p>
</li>
<li><p><strong>Decision Trees</strong> give you feature importance "for free".</p>
</li>
<li><p><strong>Solar_Radiation</strong> was the most important predictor of energy consumption.</p>
</li>
</ul>
<hr />
<h2 id="heading-assignment-3-time-series-prediction">📈 Assignment 3: Time-Series Prediction</h2>
<p>Stock price prediction is tricky! I used <code>assignment3_stock_prices.csv</code> with 90 days of trading data.</p>
<h3 id="heading-what-i-tried">What I Tried</h3>
<ol>
<li><p><strong>Polynomial Regression</strong> on <code>Day</code> vs <code>Closing_Price</code></p>
</li>
<li><p><strong>Decision Tree</strong> with multiple features</p>
</li>
<li><p><strong>Feature Engineering</strong>: Added moving averages</p>
</li>
</ol>
<h3 id="heading-the-hard-truth-i-learned">The Hard Truth I Learned</h3>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-comment"># WARNING: Time-series requires special treatment</span>
X = data[[<span class="hljs-string">'Day'</span>, <span class="hljs-string">'Volume'</span>, <span class="hljs-string">'Opening_Price'</span>]]
y = data[<span class="hljs-string">'Closing_Price'</span>]

<span class="hljs-comment"># DON'T randomly shuffle time-series data!</span>
<span class="hljs-comment"># Instead, use time-based split</span>
train_size = int(len(data) * <span class="hljs-number">0.8</span>)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
</code></pre>
<h3 id="heading-key-learning-3">Key Learning</h3>
<ul>
<li><p>Polynomial regression can capture trends but <strong>not volatility</strong>.</p>
</li>
<li><p>Decision trees struggle with sequential data unless lag features are added.</p>
</li>
<li><p><strong>Never use random shuffle</strong> for time-series data!</p>
</li>
<li><p>Financial prediction requires specialized models (ARIMA, LSTM).</p>
</li>
</ul>
<hr />
<h2 id="heading-the-grand-finale-assessment">🏁 The Grand Finale: Assessment</h2>
<p>The <code>car_price_prediction.csv</code> dataset had <strong>mixed data types</strong>, categorical variables, and complex interactions.</p>
<h3 id="heading-my-end-to-end-pipeline">My End-to-End Pipeline</h3>
<p>python</p>
<pre><code class="lang-python"><span class="hljs-comment"># 1. Load and explore</span>
data = pd.read_csv(<span class="hljs-string">'car_price_prediction.csv'</span>)
print(data.info())
print(data.describe())

<span class="hljs-comment"># 2. Handle categorical variables</span>
<span class="hljs-keyword">from</span> sklearn.preprocessing <span class="hljs-keyword">import</span> LabelEncoder, OneHotEncoder

<span class="hljs-comment"># Label encode binary categoricals</span>
le = LabelEncoder()
data[<span class="hljs-string">'Accident_History'</span>] = le.fit_transform(data[<span class="hljs-string">'Accident_History'</span>])
data[<span class="hljs-string">'Service_Records'</span>] = le.fit_transform(data[<span class="hljs-string">'Service_Records'</span>])

<span class="hljs-comment"># One-hot encode multi-category</span>
data = pd.get_dummies(data, columns=[<span class="hljs-string">'Brand'</span>, <span class="hljs-string">'Fuel_Type'</span>, <span class="hljs-string">'Transmission'</span>], drop_first=<span class="hljs-literal">True</span>)

<span class="hljs-comment"># 3. Split data</span>
X = data.drop(<span class="hljs-string">'Price'</span>, axis=<span class="hljs-number">1</span>)
y = data[<span class="hljs-string">'Price'</span>]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=<span class="hljs-number">0.2</span>, random_state=<span class="hljs-number">42</span>)

<span class="hljs-comment"># 4. Scale features (for SVR)</span>
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

<span class="hljs-comment"># 5. Train multiple models</span>
models = {
    <span class="hljs-string">'Linear Regression'</span>: LinearRegression(),
    <span class="hljs-string">'Polynomial Regression'</span>: Pipeline([
        (<span class="hljs-string">'poly'</span>, PolynomialFeatures(degree=<span class="hljs-number">2</span>)),
        (<span class="hljs-string">'linear'</span>, LinearRegression())
    ]),
    <span class="hljs-string">'SVR'</span>: SVR(kernel=<span class="hljs-string">'rbf'</span>, C=<span class="hljs-number">100</span>, gamma=<span class="hljs-number">0.1</span>),
    <span class="hljs-string">'Decision Tree'</span>: DecisionTreeRegressor(max_depth=<span class="hljs-number">5</span>, random_state=<span class="hljs-number">42</span>)
}

results = {}
<span class="hljs-keyword">for</span> name, model <span class="hljs-keyword">in</span> models.items():
    <span class="hljs-keyword">if</span> name == <span class="hljs-string">'SVR'</span>:
        <span class="hljs-comment"># Scale y for SVR</span>
        scaler_y = StandardScaler()
        y_train_scaled = scaler_y.fit_transform(y_train.values.reshape(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>)).ravel()
        model.fit(X_train_scaled, y_train_scaled)
        y_pred_scaled = model.predict(X_test_scaled)
        y_pred = scaler_y.inverse_transform(y_pred_scaled.reshape(<span class="hljs-number">-1</span>, <span class="hljs-number">1</span>))
    <span class="hljs-keyword">elif</span> name == <span class="hljs-string">'Polynomial Regression'</span>:
        model.fit(X_train, y_train)
        y_pred = model.predict(X_test)
    <span class="hljs-keyword">else</span>:
        model.fit(X_train, y_train)
        y_pred = model.predict(X_test)

    results[name] = {
        <span class="hljs-string">'MSE'</span>: mean_squared_error(y_test, y_pred),
        <span class="hljs-string">'R2'</span>: r2_score(y_test, y_pred)
    }
</code></pre>
<h3 id="heading-critical-error-encountered">⚠️ Critical Error Encountered</h3>
<p>When one-hot encoding, I initially didn't use <code>drop_first=True</code>, which led to <strong>multicollinearity</strong> (dummy variable trap). Linear regression failed with singular matrix error!</p>
<h3 id="heading-business-insights-generated">Business Insights Generated</h3>
<ul>
<li><p><code>Year</code> and <code>Mileage</code> were top predictors (from decision tree feature importance)</p>
</li>
<li><p><code>Accident_History</code> reduced price by ~15%</p>
</li>
<li><p>Electric cars had a premium of ~20%</p>
</li>
<li><p>BMW and Mercedes held value better than other brands</p>
</li>
</ul>
<h3 id="heading-final-model-performance">Final Model Performance</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Model</td><td>MSE</td><td>R² Score</td></tr>
</thead>
<tbody>
<tr>
<td>Linear Regression</td><td>4.8e+07</td><td>0.76</td></tr>
<tr>
<td>Polynomial (deg=2)</td><td>3.2e+07</td><td>0.84</td></tr>
<tr>
<td>SVR (RBF)</td><td>2.9e+07</td><td>0.86</td></tr>
<tr>
<td>Decision Tree</td><td><strong>2.5e+07</strong></td><td><strong>0.88</strong></td></tr>
</tbody>
</table>
</div><p><strong>Winner</strong>: Decision Tree Regressor (with tuning).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768948192071/b608232a-2df4-4882-95d3-18f3c575ae30.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768948262324/70fe0832-1b44-4942-ab74-1be5f246e4cb.png" alt class="image--center mx-auto" /></p>
<hr />
<h2 id="heading-troubleshooting-checklist-i-created">🛠 Troubleshooting Checklist I Created</h2>
<p>Here's a quick reference I built for myself during this journey:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Issue</td><td>Likely Cause</td><td>Solution</td></tr>
</thead>
<tbody>
<tr>
<td>Poor SVR performance</td><td>Unscaled features</td><td>Use <code>StandardScaler</code></td></tr>
<tr>
<td>Polynomial overfitting</td><td>Degree too high</td><td>Cross-validate degree choice</td></tr>
<tr>
<td>Tree too complex</td><td>No depth limit</td><td>Set <code>max_depth</code></td></tr>
<tr>
<td>Categorical data error</td><td>String values in model</td><td>Use <code>OneHotEncoder</code></td></tr>
<tr>
<td>Linear Regression singular matrix</td><td>Multicollinearity</td><td>Drop first dummy column</td></tr>
<tr>
<td>Time-series poor prediction</td><td>Random shuffle</td><td>Use time-based split</td></tr>
<tr>
<td>SVR predictions in wrong scale</td><td>Forgot inverse transform</td><td>Use <code>inverse_transform()</code></td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-resources-that-saved-me">📚 Resources That Saved Me</h2>
<ol>
<li><p><a target="_blank" href="https://scikit-learn.org/stable/"><strong>Scikit-learn Documentation</strong></a> - My bible</p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/"><strong>Stack Overflow</strong></a> - For every error message</p>
</li>
<li><p><strong>Google Colab GPU</strong> - For faster SVR training</p>
</li>
<li><p><strong>My own error log</strong> - Seriously, keep a debugging journal!</p>
</li>
</ol>
<hr />
<h2 id="heading-final-takeaways">🎯 Final Takeaways</h2>
<ol>
<li><p><strong>Start simple</strong> — always fit a linear baseline first</p>
</li>
<li><p><strong>Visualize everything</strong> — plots reveal what metrics hide</p>
</li>
<li><p><strong>Scale for SVR</strong> — non-negotiable</p>
</li>
<li><p><strong>Trees overfit</strong> — regularize with depth and sample limits</p>
</li>
<li><p><strong>Polynomial is powerful</strong> but dangerous beyond degree 4</p>
</li>
<li><p><strong>Real-world data is messy</strong> — preprocessing is 80% of the work</p>
</li>
<li><p><strong>Cross-validate everything</strong> — don't trust training scores</p>
</li>
<li><p><strong>Interpretability matters</strong> — sometimes a simpler model is better</p>
</li>
</ol>
<hr />
<h2 id="heading-pro-tip-for-learners-like-me">💡 Pro Tip for Learners Like me</h2>
<p><strong>Save every version of your notebook</strong> with descriptive names:</p>
<ul>
<li><p><code>week15_regression_v1_errors.ipynb</code></p>
</li>
<li><p><code>week15_regression_v2_fixed_scaling.ipynb</code></p>
</li>
<li><p><code>week15_regression_final.ipynb</code></p>
</li>
</ul>
<p>This way, you can trace your learning journey and never lose working versions.</p>
<hr />
<p><strong>If you're also learning regression, what was your biggest "aha" moment? Share in the comments!</strong> 👇</p>
<hr />
<p><em>Follow my journey as I document my path from ML beginner to practitioner.</em></p>
]]></content:encoded></item></channel></rss>