惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
IT之家
IT之家
博客园_首页
人人都是产品经理
人人都是产品经理
博客园 - Franky
I
InfoQ
Recent Announcements
Recent Announcements
P
Proofpoint News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
GbyAI
GbyAI
大猫的无限游戏
大猫的无限游戏
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
月光博客
月光博客
Microsoft Security Blog
Microsoft Security Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog RSS Feed
MongoDB | Blog
MongoDB | Blog
雷峰网
雷峰网
博客园 - 聂微东
N
Netflix TechBlog - Medium
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The GitHub Blog
The GitHub Blog
D
Docker

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Linear Regression: Code (a) Line
the_undefine · 2026-05-03 · via DEV Community
Cover image for Linear Regression: Code (a) Line

the_undefined_architect

It's time to write your first ML model and predict house prices.
To follow along, go ahead and take a look at the complete product:
https://github.com/yotambelgoroski/ml_unchained-house_pricing

Step 1: It's all about data

ML is all about data - you can't create a model without training it, and you can't train it without data.

Our dataset is typically split into two parts:

  1. Training data - Data used to train a model
  2. Test - Once a model is trained, we can take input (x) from the test data, predict the output (ŷ), and compare that prediction to the real value (y). This tells us how well our model performs.

In more advanced setups, you might also see a validation set, which is used to tune the model before testing it.

Where does data come from?

The answer depends on your business and use case. For learning purposes, Kaggle is a great source for datasets and ML resources. To keep things simple, I use a script that generates synthetic data.

How much data do I need for training?

There is no fixed number — as model complexity increases, more data is required.

A common rule of thumb is:
Have 10×–20× more data points than features (independent variables)

We currently have one feature (sqm), so I used 10 records to train the model — the bare minimum to keep things simple.

How much data do I need for testing?

There are several approaches, but a simple one is to split your dataset using an 80:20 ratio:

  • 80% for training
  • 20% for testing

Step 2: Training the model

Now that we have our dataset, it's time to train a model.

Training involves three steps:

  1. Load the training data
  2. Train the model in memory based on that data
  3. Serialization — save the trained model to disk so it can be reused without retraining

Here is how it looks in code:

import joblib
import pandas as pd
from pathlib import Path
from sklearn.linear_model import LinearRegression

FEATURE_COLS = ["sqm"]
TARGET_COL = "price"
MODEL_FILENAME = "house_price_model.joblib"


def load_training_data(train_path: Path) -> pd.DataFrame:
    return pd.read_csv(train_path)


def train_model(df: pd.DataFrame) -> LinearRegression:
    model = LinearRegression()
    model.fit(df[FEATURE_COLS], df[TARGET_COL])
    return model


def save_model(model: LinearRegression, dest_path: Path) -> None:
    dest_path.parent.mkdir(parents=True, exist_ok=True)
    joblib.dump(model, dest_path)
    print(f"Model saved → {dest_path}")


def train(train_path: Path, model_dir: Path) -> LinearRegression:
    df = load_training_data(train_path)
    model = train_model(df)
    save_model(model, model_dir / MODEL_FILENAME)
    print(f"Model trained on {len(df)} samples.")
    return model 

Enter fullscreen mode Exit fullscreen mode

This is it - our first model!

Our Dependencies

  • Pandas — A data handling library for working with tabular data. Its core structure, the DataFrame, allows us to easily access and manipulate data.
  • scikit-learn — A machine learning library for Python. LinearRegression is one of its models, used to learn the best linear relationship between input features and a target value.
  • Joblib — A utility library used here for serialization. It allows us to save a trained model to disk and load it later for inference.

Congratulations — you've created your first model!

However, it's not production-ready yet. Next, we’ll use the test data to evaluate how good our model really is.