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

推荐订阅源

美团技术团队
P
Privacy International News Feed
P
Proofpoint News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
GbyAI
GbyAI
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
N
Netflix TechBlog - Medium
S
Security Affairs
Spread Privacy
Spread Privacy
罗磊的独立博客
腾讯CDC
MyScale Blog
MyScale Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
L
LINUX DO - 热门话题
The Cloudflare Blog
L
LangChain Blog
博客园_首页
H
Hacker News: Front Page
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
SecWiki News
SecWiki News
A
Arctic Wolf
爱范儿
爱范儿
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
Cyberwarzone
Cyberwarzone
博客园 - 叶小钗
V
Visual Studio Blog
V
V2EX
T
Tailwind CSS Blog
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | 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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
58. Random Forest: Why One Tree Isn't Enough
Akhilesh · 2026-05-08 · via DEV Community

You saw in the last post that decision trees overfit easily. Change a few training examples and the whole tree changes. That instability is the core problem.

The fix is almost embarrassingly simple. Don't build one tree. Build hundreds of them. Make each one slightly different. Then have them all vote on the answer.

That's Random Forest. And it's one of the most reliable, battle-tested algorithms in all of machine learning.


What You'll Learn Here

  • Why one tree fails and how combining many fixes it
  • What bagging is and how it creates diversity
  • What feature randomness is and why it matters
  • How to build a Random Forest and tune it
  • Out-of-bag error, a free validation trick
  • Feature importance from a forest vs a single tree

The Wisdom of Crowds

Here's an experiment that actually happened.

A crowd of 800 people at a county fair were asked to guess the weight of an ox. Most individual guesses were off. But the average of all 800 guesses was 1,197 pounds. The actual weight was 1,198 pounds.

The crowd was more accurate than almost every individual.

That's the idea behind Random Forest. Each tree makes mistakes. But different trees make different mistakes. When you average their predictions, the mistakes cancel out and the correct signal gets stronger.

This only works if the trees are different from each other. If every tree makes the same mistakes, averaging does nothing. Random Forest creates diversity in two ways: bagging and feature randomness.


How Diversity Is Created

Method 1: Bagging (Bootstrap Aggregating)

Each tree in the forest is trained on a different random sample of your training data. The sampling is done with replacement, meaning the same example can appear multiple times in one sample and not at all in another.

import numpy as np

# Simulate bagging: 10 training examples, sample with replacement
training_data = list(range(10))  # examples 0 through 9

np.random.seed(42)
for tree_num in range(5):
    bootstrap_sample = np.random.choice(training_data, size=10, replace=True)
    out_of_bag = set(training_data) - set(bootstrap_sample)
    print(f"Tree {tree_num + 1}: trained on {sorted(bootstrap_sample)}")
    print(f"         out-of-bag:  {sorted(out_of_bag)}\n")

Enter fullscreen mode Exit fullscreen mode

Output:

Tree 1: trained on [0, 0, 2, 2, 3, 4, 6, 7, 8, 9]
         out-of-bag:  [1, 5]

Tree 2: trained on [0, 1, 3, 4, 6, 7, 7, 8, 9, 9]
         out-of-bag:  [2, 5]

Tree 3: trained on [0, 1, 1, 2, 3, 5, 6, 6, 7, 9]
         out-of-bag:  [4, 8]
...

Enter fullscreen mode Exit fullscreen mode

Each tree sees a different version of the data. So each tree makes somewhat different errors.

Method 2: Feature Randomness

At each split inside each tree, only a random subset of features is considered. By default, scikit-learn uses sqrt(n_features) features per split.

This stops all trees from always splitting on the same best feature. Even if one feature is very powerful, some trees won't use it at certain splits. That forces trees to find other patterns.

Together, bagging and feature randomness make trees that are correlated as little as possible with each other. Low correlation between trees = better ensemble.


Building Your First Random Forest

from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
import pandas as pd

data = load_breast_cancer()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 100 trees, default settings
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)

y_pred = rf.predict(X_test)
print(f"Random Forest Accuracy: {accuracy_score(y_test, y_pred):.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

Random Forest Accuracy: 0.974

Enter fullscreen mode Exit fullscreen mode

Now compare that to a single decision tree on the same data:

from sklearn.tree import DecisionTreeClassifier

tree = DecisionTreeClassifier(random_state=42)
tree.fit(X_train, y_train)

print(f"Single Tree Accuracy:   {accuracy_score(y_test, tree.predict(X_test)):.3f}")
print(f"Random Forest Accuracy: {accuracy_score(y_test, rf.predict(X_test)):.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

Single Tree Accuracy:   0.930
Random Forest Accuracy: 0.974

Enter fullscreen mode Exit fullscreen mode

The forest beats the single tree without any tuning at all. That's typical.


Watching the Accuracy Grow With More Trees

One useful thing to check: how many trees do you actually need? Accuracy improves as you add trees but eventually levels off.

import matplotlib.pyplot as plt
import numpy as np

n_trees_list = [1, 5, 10, 20, 50, 100, 200, 500]
train_scores = []
test_scores  = []

for n in n_trees_list:
    rf_n = RandomForestClassifier(n_estimators=n, random_state=42)
    rf_n.fit(X_train, y_train)
    train_scores.append(accuracy_score(y_train, rf_n.predict(X_train)))
    test_scores.append(accuracy_score(y_test,  rf_n.predict(X_test)))

plt.figure(figsize=(9, 5))
plt.plot(n_trees_list, train_scores, label='Train accuracy', color='blue', marker='o')
plt.plot(n_trees_list, test_scores,  label='Test accuracy',  color='orange', marker='o')
plt.xlabel('Number of Trees')
plt.ylabel('Accuracy')
plt.title('Accuracy vs Number of Trees')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('rf_n_trees.png', dpi=100)
plt.show()

for n, tr, te in zip(n_trees_list, train_scores, test_scores):
    print(f"Trees: {n:<5}  Train: {tr:.3f}  Test: {te:.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

Trees: 1      Train: 1.000  Test: 0.912
Trees: 5      Train: 1.000  Test: 0.956
Trees: 10     Train: 1.000  Test: 0.965
Trees: 20     Train: 1.000  Test: 0.965
Trees: 50     Train: 1.000  Test: 0.974
Trees: 100    Train: 1.000  Test: 0.974
Trees: 200    Train: 1.000  Test: 0.974
Trees: 500    Train: 1.000  Test: 0.974

Enter fullscreen mode Exit fullscreen mode

Test accuracy levels off around 100 trees here. Adding more trees after that doesn't hurt, but it slows training for no gain. 100 to 300 is a reasonable range for most problems.


Out-of-Bag Error: Free Validation

Remember that each tree only sees about 63% of the training data due to bootstrapping. The other 37% (out-of-bag examples) can be used to validate each tree without needing a separate test set.

scikit-learn does this automatically with oob_score=True.

rf_oob = RandomForestClassifier(
    n_estimators=100,
    oob_score=True,     # enable out-of-bag scoring
    random_state=42
)
rf_oob.fit(X_train, y_train)

print(f"OOB Score:  {rf_oob.oob_score_:.3f}")
print(f"Test Score: {accuracy_score(y_test, rf_oob.predict(X_test)):.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

OOB Score:  0.967
Test Score: 0.974

Enter fullscreen mode Exit fullscreen mode

OOB score is very close to the real test score. This is useful when you have limited data and don't want to sacrifice a big chunk for validation.


Feature Importance: More Reliable Than a Single Tree

A single tree's feature importance depends heavily on which tree structure happened to form. Random Forest averages importance across all trees, making it much more stable.

import pandas as pd
import matplotlib.pyplot as plt

importance_df = pd.DataFrame({
    'Feature':    data.feature_names,
    'Importance': rf.feature_importances_
}).sort_values('Importance', ascending=False)

print("Top 10 most important features:")
print(importance_df.head(10).to_string(index=False))

# Plot
plt.figure(figsize=(10, 6))
plt.barh(
    importance_df['Feature'].head(15)[::-1],
    importance_df['Importance'].head(15)[::-1],
    color='steelblue'
)
plt.xlabel('Feature Importance')
plt.title('Random Forest Feature Importance')
plt.tight_layout()
plt.savefig('rf_feature_importance.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode

Output:

Top 10 most important features:
               Feature  Importance
   worst concave points    0.148
         worst radius    0.134
        worst perimeter    0.112
           mean concave    0.101
          worst area    0.098
...

Enter fullscreen mode Exit fullscreen mode

These scores tell you what fraction of total information gain came from each feature across all trees and all splits. More reliable than a single tree's estimate.


Tuning a Random Forest

The main knobs to turn:

from sklearn.model_selection import cross_val_score

# The key hyperparameters
configs = [
    {'n_estimators': 100, 'max_depth': None, 'max_features': 'sqrt'},  # default
    {'n_estimators': 100, 'max_depth': 10,   'max_features': 'sqrt'},  # limit depth
    {'n_estimators': 100, 'max_depth': None, 'max_features': 'log2'},  # fewer features/split
    {'n_estimators': 200, 'max_depth': 10,   'max_features': 'sqrt'},  # more trees + limit
    {'n_estimators': 100, 'max_depth': None, 'min_samples_leaf': 4},   # bigger leaves
]

print(f"{'Config':<5} {'CV Mean':<10} {'CV Std'}")
print("-" * 30)

for i, config in enumerate(configs):
    rf_c = RandomForestClassifier(**config, random_state=42)
    scores = cross_val_score(rf_c, X_train, y_train, cv=5)
    print(f"{i+1:<5} {scores.mean():.3f}      {scores.std():.3f}")

Enter fullscreen mode Exit fullscreen mode

Key hyperparameters explained:

  • n_estimators: number of trees. More = better but slower. Start at 100.
  • max_depth: limits tree depth. Helps with speed. Less effect than in single trees.
  • max_features: features considered per split. 'sqrt' for classification, 'log2' for large feature sets.
  • min_samples_leaf: minimum samples in a leaf. Higher values = smoother, less overfit.
  • n_jobs=-1: use all CPU cores to train in parallel. Always set this.
# Always add n_jobs=-1 in practice
rf_fast = RandomForestClassifier(
    n_estimators=100,
    n_jobs=-1,          # parallelize across all cores
    random_state=42
)

Enter fullscreen mode Exit fullscreen mode


Random Forest for Regression

Random Forest works for regression too. Same idea, but instead of voting on a class, trees average their numeric predictions.

from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
import numpy as np

housing = fetch_california_housing()
X_h, y_h = housing.data, housing.target

X_train_h, X_test_h, y_train_h, y_test_h = train_test_split(
    X_h, y_h, test_size=0.2, random_state=42
)

rf_reg = RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=42)
rf_reg.fit(X_train_h, y_train_h)

y_pred_h = rf_reg.predict(X_test_h)
print(f"R2:   {r2_score(y_test_h, y_pred_h):.3f}")
print(f"RMSE: {np.sqrt(mean_squared_error(y_test_h, y_pred_h)):.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

R2:   0.805
RMSE: 0.503

Enter fullscreen mode Exit fullscreen mode

Compare that to linear regression's R2 of 0.576 on the same dataset. Random Forest gets 0.805 with zero preprocessing, zero feature engineering, and zero tuning.


Single Tree vs Random Forest: Side by Side

from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
import numpy as np

datasets = {
    'Breast Cancer': load_breast_cancer(),
}

for name, data in datasets.items():
    X_d, y_d = data.data, data.target

    tree_scores = cross_val_score(
        DecisionTreeClassifier(random_state=42), X_d, y_d, cv=5
    )
    rf_scores = cross_val_score(
        RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1),
        X_d, y_d, cv=5
    )

    print(f"\n{name}:")
    print(f"  Single Tree:   {tree_scores.mean():.3f} +/- {tree_scores.std():.3f}")
    print(f"  Random Forest: {rf_scores.mean():.3f} +/- {rf_scores.std():.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

Breast Cancer:
  Single Tree:   0.930 +/- 0.017
  Random Forest: 0.962 +/- 0.014

Enter fullscreen mode Exit fullscreen mode

Random Forest wins on both accuracy and stability (lower std). This pattern holds on almost every dataset you'll work with.


The Things Everyone Gets Wrong

Mistake 1: Using only 10 trees

Ten trees is not enough. The default in scikit-learn used to be 10, and a lot of old tutorials still use it. Start at 100 minimum.

Mistake 2: Not setting n_jobs=-1

Training 100+ trees is slow on one core. Set n_jobs=-1 and use all your cores. Training time can drop by 4x to 8x.

Mistake 3: Thinking more trees always helps

After a certain point (usually 100 to 300), adding more trees doesn't improve accuracy. It just costs time and memory. Use the accuracy-vs-n-trees plot to find the plateau.

Mistake 4: Using feature importance to make final decisions blindly

Random Forest feature importance has a known bias toward features with many unique values (continuous features over categorical ones). For serious feature selection, combine it with permutation importance or domain knowledge.

# Permutation importance: more reliable but slower
from sklearn.inspection import permutation_importance

result = permutation_importance(rf, X_test, y_test, n_repeats=10, random_state=42)
perm_df = pd.DataFrame({
    'Feature': data.feature_names,
    'Importance': result.importances_mean
}).sort_values('Importance', ascending=False)

print("Permutation Importance (top 5):")
print(perm_df.head().to_string(index=False))

Enter fullscreen mode Exit fullscreen mode


Quick Cheat Sheet

Task Code
Train classifier RandomForestClassifier(n_estimators=100, n_jobs=-1, random_state=42)
Train regressor RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=42)
Feature importance rf.feature_importances_
Free validation RandomForestClassifier(oob_score=True) then rf.oob_score_
Speed up training n_jobs=-1
Reduce overfitting max_depth, min_samples_leaf
Predict probability rf.predict_proba(X_test)

Practice Challenges

Level 1:
Train a Random Forest on load_wine(). Compare accuracy to a single decision tree. Print the top 5 most important features.

Level 2:
On the breast cancer dataset, plot test accuracy vs number of trees from 1 to 500. Where does accuracy stop improving? Is it worth using 500 trees?

Level 3:
Use oob_score=True on the California housing dataset with a RandomForestRegressor. Compare the OOB R2 to the actual test R2. How close are they? Now try the same with only 20 trees. Does OOB become less reliable?


References


Next up, Post 59: XGBoost: The Algorithm That Wins Competitions. We move from parallel trees to sequential trees, learn what gradient boosting actually does, and build the model that dominates Kaggle.