Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Vectorization ใน Python: ทำไมถึงเร็วกว่า Loop และใช้อย่างไร?

Vectorization เป็นเทคนิคการคำนวณแบบเวกเตอร์/เมทริกซ์ที่ดำเนินการบน Array ทั้งหมดพร้อมกัน แทนที่จะใช้ Loop วนลูปทีละองค์ประกอบ ทำให้โค้ดสั้นขึ้น อ่านง่ายขึ้น และ เร็วขึ้นมาก เนื่องจากใช้ Low-level Optimized Libraries (BLAS, LAPACK, SIMD)

ทำไม Vectorization จึงเร็ว?

  • No Python Loop Overhead: ลด Overhead ของ Interpreter ในแต่ละ Iteration
  • Contiguous Memory: ข้อมูลเก็บติดกันในหน่วยความจำ (Cache Friendly)
  • SIMD Instructions: CPU ทำคำนวณหลายค่าพร้อมกัน (Single Instruction, Multiple Data)
  • Optimized BLAS/LAPACK: ใช้ไลบรารีคณิตศาสตร์ที่ปรับแต่งแล้ว (OpenBLAS, MKL, ATLAS)

ตัวอย่างเปรียบเทียบ: Dot Product

import time
import numpy as np
from array import array

# สร้างข้อมูลทดสอบ
size = 100_000
p = array('d', range(size, size * 2))
q = array('d', range(size * 2, size * 3))

# 1. Classic Python Loop
tic = time.perf_counter()
dot_value = 0.0
for i in range(len(p)):
    dot_value += p[i] * q[i]
toc = time.perf_counter()
print(f"Loop: {dot_value:.2f}, Time: {(toc - tic)*1000:.2f} ms")

# 2. NumPy Vectorized
n_tic = time.perf_counter()
n_dot_product = np.dot(p, q)
n_toc = time.perf_counter()
print(f"NumPy: {n_dot_product:.2f}, Time: {(n_toc - n_tic)*1000:.2f} ms")

# 3. NumPy Arrays (เร็วกว่าอีก)
np_p = np.arange(size, size * 2, dtype=np.float64)
np_q = np.arange(size * 2, size * 3, dtype=np.float64)

np_tic = time.perf_counter()
np_result = np.dot(np_p, np_q)
np_toc = time.perf_counter()
print(f"NumPy Array: {np_result:.2f}, Time: {(np_toc - np_tic)*1000:.2f} ms")

ผลลัพธ์ทั่วไป

Loop: 3833313333350000.00, Time: 116.52 ms
NumPy: 3833313333350000.00, Time: 2.54 ms
NumPy Array: 3833313333350000.00, Time: 0.85 ms

NumPy เร็วกว่า Loop ประมาณ 40-100 เท่า!

ฟังก์ชัน NumPy สำคัญสำหรับ Vectorization

ฟังก์ชันคำอธิบายตัวอย่าง
np.dot(a, b)Dot Product / Matrix MultiplicationInner product ของเวกเตอร์ หรือ Matrix multiplication
np.outer(a, b)Outer Productสร้างเมทริกซ์ขนาด (m×n) จากเวกเตอร์สองตัว
np.multiply(a, b)Element-wise Multiplicationคูณองค์ประกอบตำแหน่งเดียวกัน
np.add/subtract/divideElement-wise Arithmetic+, -, /, * ระหว่าง Array
np.sum/mean/stdAggregationผลรวม, ค่าเฉลี่ย, ส่วนเบี่ยงเบนมาตรฐาน
np.zeros((n,m))สร้าง Array แบบศูนย์Initialize buffer

Broadcasting: Vectorization ขั้นสูง

NumPy สามารถดำเนินการระหว่าง Array ขนาดต่างกันได้โดยอัตโนมัติ

import numpy as np

# Matrix (3,3) + Vector (3,) -> Broadcast vector ทุกแถว
matrix = np.array([[1,2,3], [4,5,6], [7,8,9]])
vector = np.array([10, 20, 30])

result = matrix + vector
print(result)
# [[11 22 33]
#  [14 25 36]
#  [17 28 39]]

เมื่อไหร่ควรใช้ Vectorization?

  • ✅ การคำนวณตัวเลขจำนวนมาก (Numerical Computing)
  • ✅ Linear Algebra, Statistics, Signal Processing
  • ✅ Machine Learning Data Preprocessing
  • ❌ Logic ที่ซับซ้อน/มีเงื่อนไขเยอะ (Complex Conditional Logic)
  • ❌ ข้อมูลขนาดเล็กมาก (Overhead ของ NumPy อาจสูงกว่า)

สรุป

Vectorization เป็นหัวใจสำคัญของ High-performance Python ใน Data Science การใช้ NumPy/Pandas อย่างถูกต้องแทน Loop แบบ Python ธรรมดาจะทำให้โค้ด เร็วขึ้น 10-100 เท่า และ สั้น/อ่านง่ายขึ้น ควรฝึกฝนคิดในรูปแบบ Array Operations แทน Element-wise Loops