循环的终结:资深数据科学家为何用向量思考

发布: (2026年1月11日 GMT+8 02:25)
5 min read
原文: Dev.to

Source: Dev.to

在传统的软件开发中,迭代 是王道。我们被教导要顺序思考:取一个项目,处理它,存储结果,然后移动到下一个。然而,当我们进入 大数据机器学习 的领域时,这种线性方法成为了导致性能瓶颈的根源。

如果你只在电子表格中处理 10 行数据,for 循环几乎可以忽略不计。如果你要用 1000 万条金融记录来训练模型,for 循环就是不可接受的。

今天,我们将探讨使用 NumPy 进行 向量化 的概念——它是 Pandas 和 Scikit‑Learn 背后的数学引擎,并说明掌握计算线性代数为何是数据科学的真正入门门槛。

Article illustration

反模式:标量迭代

让我们想象一个真实的金融场景。我们有两个列表,各包含 100 万个股票价格(收盘价和开盘价),并且我们想计算每日波动率(百分比差异)。

朴素的做法(纯 Python)如下:

import time
import random

# Generating 1 million simulated data points
close_prices = [random.uniform(100, 200) for _ in range(1_000_000)]
open_prices = [random.uniform(100, 200) for _ in range(1_000_000)]

def calculate_volatility_loops(close_p, open_p):
    result = []
    start_time = time.time()

    # The Bottleneck: Explicit Iteration
    for c, o in zip(close_p, open_p):
        difference = (c - o) / o
        result.append(difference)

    print(f"Loop Time: {time.time() - start_time:.4f} seconds")
    return result

# Execution
volatility = calculate_volatility_loops(close_prices, open_prices)

问题: Python 是一种解释型、动态语言。在每一次迭代中,解释器必须验证数据类型、分配内存并管理指针。这个开销乘以一百万次后,会严重破坏性能。

解决方案:广播与 SIMD

这就是 NumPy 和“向量思维”发挥作用的地方。我们不再逐个数字处理,而是使用连续的内存结构(数组)和利用现代 CPU SIMD(单指令多数据)指令的优化 C‑operations。

import time
import numpy as np

# Converting lists to NumPy arrays
np_close = np.array(close_prices)
np_open = np.array(open_prices)

def calculate_volatility_vectorized(close_p, open_p):
    start_time = time.time()

    # The Magic: Vectorized Operation
    # No visible loops. The operation applies to the entire array in parallel.
    result = (close_p - open_p) / open_p

    print(f"Vectorized Time: {time.time() - start_time:.4f} seconds")
    return result

# Execution
volatility_np = calculate_volatility_vectorized(np_close, np_open)

结果: 通常,NumPy 版本快 50 到 100 倍

分析复杂度:布尔掩码

Power doesn’t stop at basic arithmetic. A Data Scientist must interrogate the data. Suppose we want to filter only those days where volatility exceeded 5 % (market anomalies).

# Create a mask (an array of True/False values)
high_risk_mask = volatility_np > 0.05

# Apply the mask to the original dataset
critical_days = np_close[high_risk_mask]

print(f"High volatility days detected: {len(critical_days)}")

This code is declarative (“give me the data that meets X”) rather than imperative (“go through, check, save”). It is cleaner, less bug‑prone, and mathematically elegant.

从程序员到数据科学家

了解如何使用库与掌握其背后科学的差距决定了你的职业上限。像 Pandas 这样的工具是建立在这些 NumPy 原理之上的抽象。如果你不理解多维数组和 broadcasting 的工作方式,就永远无法优化机器学习模型或处理真实的大数据。

Python Baires,我们不只是教语法。我们的 Module 4: Data Science & Advanced Backend 深入探讨构建所需的计算线性代数,包括:

  • 预测模型: 从数学基础出发的回归和分类。
  • 科学仪表盘: 使用 Matplotlib 和 Plotly 实现交互式可视化。
  • 高性能后端: 将复杂计算集成到 RESTful API 中。

你准备好抛弃循环思维,开始用向量思考了吗?
探索完整课程大纲并加入下期 cohort at 。

真实的数据工程,解决真实的问题。

Back to Blog

相关文章

阅读更多 »

使用线性回归预测员工薪资

使用线性回归的薪资预测 !Njeri Muriithi https://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2F...

介绍:使用 AI 分析随机性

大家好!👋 我目前正在进行 NichebrAI 项目,在这个项目中,我正在尝试使用 machine learning models 来分析彩票的历史数据……

机器学习 - 完整课程

机器学习 — 博客系列目录 第0部分:ML 之前的思维方式与宏观视角 - 什么是机器学习?去除流行词汇 - ML 与 AI 与 DL 与 Statistics - …