ရိုးရိုးလေး ရှင်းပြမယ်
NumPy ကို ရိုးရိုးလေး ပြောရရင်
NumPy ဆိုတာ Python မှာ ကိန်းဂဏန်း အများကြီးကို မြန်မြန်ဆန်ဆန် တွက်ဖို့ သုံးတဲ့ library ပါ။ သူ့ရဲ့ အဓိက အရာက ndarray လို့ ခေါ်တဲ့ array ပါ — type တူတဲ့ value တွေကို memory ထဲမှာ ကပ်လျက် စီထားတဲ့ ဇယားကွက်တစ်ခုပါ။ Python list က object အမျိုးမျိုးကို ညွှန်ပြတဲ့ pointer တွေ စုထားတာဖြစ်ပြီး NumPy array ကတော့ raw number တွေကိုပဲ တန်းစီ သိမ်းထားပါတယ်။
Spreadsheet တစ်ခုမှာ cell တစ်ခုချင်းစီကို လက်နဲ့ မပြင်ဘဲ column တစ်ခုလုံးကို formula တစ်ကြောင်းနဲ့ တွက်လိုက်သလိုပါပဲ။ NumPy မှာ scores * 2 လို့ ရေးလိုက်ရင် cell တိုင်းကို နှစ်ဆ မြှောက်ပေးပြီး loop ကို C နဲ့ ရေးထားတဲ့ code ထဲမှာ run ပေးလို့ Python loop ထက် အဆပေါင်းများစွာ မြန်ပါတယ်။
Problem → Why → Solution
ပြဿနာ: list နဲ့ loop တွေ နှေးပြီး ရှုပ်လာတယ်
ကျောင်းသား ၃ ယောက်ရဲ့ quiz ၄ ခု အမှတ်ကို list of lists နဲ့ သိမ်းထားတယ် ဆိုပါစို့။ ကျောင်းသားတစ်ယောက်ချင်းရဲ့ ပျမ်းမျှ၊ quiz တစ်ခုချင်းရဲ့ ပျမ်းမျှ၊ percentage ပြောင်းတာ — အလုပ်တစ်ခုစီအတွက် nested loop တစ်ခုစီ ရေးရပါတယ်။ ကျောင်းသား တစ်သိန်းဖြစ်လာရင် အဲဒီ loop တွေက စက္ကန့်ပေါင်းများစွာ ကြာလာပြီး index မှားတဲ့ bug တွေကလည်း ဝင်လာလွယ်ပါတယ်။
scores = [[40, 35, 48, 42], [28, 31, 25, 30], [45, 50, 47, 49]]
quiz_means = []
for q in range(4):
total = 0
for row in scores:
total += row[q]
quiz_means.append(total / len(scores))
percent = [[s / 50 * 100 for s in row] for row in scores]
doubled = scores * 2 # surprise: repeats the list, does not double the marksဘာကြောင့် NumPy လိုလဲ
Loop တွေက 'ဘယ်လိုလုပ်ရမလဲ' ကို ပြောနေပြီး 'ဘာကို လိုချင်တာလဲ' ကို ဖုံးကွယ်ထားပါတယ်။ နောက်ဆုံး line ကလည်း list ပေါ်မှာ * က သင်္ချာ မဟုတ်ဘဲ list ကို ထပ်ပွားတာဖြစ်လို့ ထောင်ချောက်ပါ။ NumPy နဲ့ဆိုရင် scores.mean(axis=0) တစ်ကြောင်းက quiz ပျမ်းမျှကို ပေးပြီး scores * 2 က တကယ်ပဲ အမှတ်တိုင်းကို နှစ်ဆ မြှောက်ပေးပါတယ်။
Core concept: shape, dtype, axis နဲ့ broadcasting
Array တိုင်းမှာ အရေးကြီးတဲ့ attribute နှစ်ခု ရှိပါတယ်။ shape က dimension တစ်ခုစီမှာ element ဘယ်နှစ်ခု ရှိလဲ ပြောပြတဲ့ tuple ပါ: row ၃ ခု column ၄ ခုရှိတဲ့ ဇယားဆိုရင် (3, 4) ပါ။ dtype ကတော့ cell တိုင်းရဲ့ type ပါ — int64, float64, bool စသည်ဖြင့်ပါ။ Array တစ်ခုမှာ dtype တစ်ခုတည်းပဲ ရှိနိုင်လို့ integer နဲ့ float ရောထည့်ရင် အားလုံးကို float64 ပြောင်းလိုက်ပါတယ်။ Integer dtype တွေမှာ အကန့်အသတ် ရှိတာကိုလည်း သတိပြုပါ: Python int လို အကြီးကြီး ကြီးမလာဘဲ int8 ဆိုရင် 127 ကျော်တာနဲ့ wrap around ဖြစ်သွားပါတယ်။
Vectorized operation ဆိုတာ array နှစ်ခုကြား (ဒါမှမဟုတ် array နဲ့ number ကြား) +, -, *, /, ** နဲ့ comparison တွေကို element တစ်ခုချင်းစီအလိုက် တွက်ပေးတာပါ။ a * b က matrix multiplication မဟုတ်ပါဘူး၊ နေရာတူ element တွေကို မြှောက်တာပါ။ Matrix product လိုချင်ရင် a @ b ကို သုံးပါ။ Comparison တစ်ခုက True/False array ပြန်ပေးပြီး အဲဒါကို mask အဖြစ် scores[mask] လို သုံးရင် True ဖြစ်တဲ့ element တွေကိုပဲ ရွေးထုတ်ပေးပါတယ်။
Reduction function တွေ (sum, mean, max, min, std) က axis argument ကို လက်ခံပါတယ်။ axis ဆိုတာ 'ဘယ် dimension ကို ချေဖျက်ပစ်မလဲ' ပါ။ (3, 4) array မှာ axis=0 က row တွေကို ပေါင်းချေလို့ column တစ်ခုစီအတွက် ရလဒ် ၄ ခု ရပြီး axis=1 က column တွေကို ချေလို့ row တစ်ခုစီအတွက် ရလဒ် ၃ ခု ရပါတယ်။
| Expression | (3, 4) array ပေါ်က ရလဒ် |
|---|---|
| a.sum() | number တစ်ခုတည်း (cell ၁၂ ခုလုံး ပေါင်း) |
| a.mean(axis=0) | shape (4,): column တစ်ခုစီရဲ့ ပျမ်းမျှ |
| a.mean(axis=1) | shape (3,): row တစ်ခုစီရဲ့ ပျမ်းမျှ |
Broadcasting ကတော့ shape မတူတဲ့ array တွေကို တွဲတွက်ခွင့်ပေးတဲ့ rule ပါ။ NumPy က shape တွေကို ညာဘက်ကနေ စတိုက်စစ်ပါတယ်: dimension နှစ်ခုဟာ တူရင် ဒါမှမဟုတ် တစ်ခုက 1 ဖြစ်ရင် ကိုက်ညီပါတယ်။ ဒါကြောင့် (3, 4) နဲ့ (4,) ကို ပေါင်းရင် (4,) ကို row ၃ ခုလုံးပေါ် ဖြန့်ပေးပါတယ်။ (3, 4) နဲ့ (3,) ကတော့ 4 နဲ့ 3 မကိုက်လို့ error တက်ပါတယ်၊ row အလိုက် ပေါင်းချင်ရင် shape (3, 1) ဖြစ်အောင် ပြောင်းရပါတယ်။
- shape နဲ့ dtype ကို အရင် စစ်
- operation က cell တိုင်းကို တစ်ပြိုင်နက် ထိ
- axis က ဘယ် dimension ချေမလဲ ရွေး
- shape မတူရင် ညာဘက်ကနေ broadcast စစ်
Code တစ်ကြောင်း ရေးတိုင်း 'ဒီရလဒ်ရဲ့ shape က ဘာဖြစ်မလဲ' လို့ မေးကြည့်ပါ၊ NumPy bug အများစုက shape မှားတာကနေ စပါတယ်။
အထွေထွေ ပုံစံ
import numpy as np
arr = np.array(nested_values, dtype=np.float64)
arr.shape, arr.dtype
result = arr * factor + offset # element-wise
per_column = arr.mean(axis=0) # collapse rows
per_row = arr.sum(axis=1) # collapse columns
subset = arr[arr > threshold] # boolean mask
view = arr[:, col] # slice = view
safe = arr[:, col].copy() # independent copyArray ဆောက်ပါ၊ shape နဲ့ dtype ကို စစ်ပါ၊ ပြီးရင် loop အစား expression တွေ, axis ပါတဲ့ reduction တွေ နဲ့ mask တွေကို သုံးပါ။ Slice ကို သီးခြား ပြင်ချင်ရင် .copy() ထည့်ပါ။
Worked example: quiz အမှတ် ဇယား
အောက်က program က ကျောင်းသား ၃ ယောက်၊ quiz ၄ ခု (တစ်ခုကို အမှတ် ၅၀) ရှိတဲ့ ဇယားကို အသုံးပြုပါတယ်။ Problem section က loop တွေ အားလုံးကို expression တစ်ကြောင်းစီနဲ့ အစားထိုးထားပြီး နောက်ဆုံးမှာ slice ကို ပြင်လိုက်ရင် original array ပါ ပြောင်းသွားကြောင်း သက်သေပြထားပါတယ်။
import numpy as np
# 3 students x 4 quizzes, each quiz out of 50
scores = np.array([
[40, 35, 48, 42],
[28, 31, 25, 30],
[45, 50, 47, 49],
])
print("shape:", scores.shape, "dtype:", scores.dtype)
percent = scores / 50 * 100 # one expression, every cell
print("student 0 (%):", percent[0])
print("mean per student:", scores.mean(axis=1))
print("mean per quiz: ", scores.mean(axis=0))
bonus = np.array([2, 0, 5, 0]) # shape (4,) is stretched over 3 rows
curved = np.minimum(scores + bonus, 50)
print("curved:")
print(curved)
passed = scores.mean(axis=1) >= 35 # boolean mask, one per student
print("passed:", passed, "count:", passed.sum())
print("passing rows:")
print(scores[passed])
quiz3 = scores[:, 2] # slicing gives a VIEW
quiz3[0] = 0
print("after editing the slice, scores[0, 2] =", scores[0, 2])Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Inspect first
print("shape:", scores.shape, "dtype:", scores.dtype)(3, 4) နဲ့ int64 ကို ပြပါတယ်။ Integer တွေချည်း ထည့်ထားလို့ dtype က integer ဖြစ်ပါတယ်၊ 64-bit platform အများစုမှာ int64 ပါ။
- Vectorized maths
percent = scores / 50 * 100 # one expression, every cellCell ၁၂ ခုလုံးကို တစ်ပြိုင်နက် တွက်ပါတယ်။ / က အမြဲ float ပြန်ပေးလို့ ရလဒ်က float64 ဖြစ်ပြီး 80. လို dot ပါတဲ့ ပုံစံနဲ့ print ထွက်ပါတယ်။
- Choose the axis
print("mean per student:", scores.mean(axis=1))axis=1 က quiz column တွေကို ချေလို့ ကျောင်းသားတစ်ယောက်ကို ပျမ်းမျှ တစ်ခုစီ ရပါတယ်။ နောက်တစ်ကြောင်းက axis=0 နဲ့ quiz တစ်ခုချင်းရဲ့ ပျမ်းမျှကို ပေးပါတယ်။
- Broadcast a vector
curved = np.minimum(scores + bonus, 50)bonus ရဲ့ shape (4,) က row တိုင်းပေါ် ဖြန့်သွားလို့ quiz 1 မှာ 2 မှတ်၊ quiz 3 မှာ 5 မှတ် ပေါင်းပေးပါတယ်။ np.minimum က 50 ထက် မကျော်အောင် ကန့်သတ်ပါတယ်။
- Mask rows
print(scores[passed])passed က ကျောင်းသားတစ်ယောက်ကို True/False တစ်ခုစီ ပါတဲ့ shape (3,) array ပါ။ Index အဖြစ် သုံးလိုက်တော့ True ဖြစ်တဲ့ row တွေကိုပဲ copy အသစ်အဖြစ် ပြန်ပေးပါတယ်။ passed.sum() က True ကို 1 လို့ ရေတွက်ပါတယ်။
- A view, not a copy
quiz3 = scores[:, 2] # slicing gives a VIEWBasic slicing က data ကို copy မကူးဘဲ memory တူတူကို ကြည့်တဲ့ view ကို ပြန်ပေးပါတယ်။ ဒါကြောင့် quiz3[0] = 0 က scores[0, 2] ကိုပါ 0 ဖြစ်သွားစေပါတယ်။
shape: (3, 4) dtype: int64
student 0 (%): [80. 70. 96. 84.]
mean per student: [41.25 28.5 47.75]
mean per quiz: [37.66666667 38.66666667 40. 40.33333333]
curved:
[[42 35 50 42]
[30 31 30 30]
[47 50 50 49]]
passed: [ True False True] count: 2
passing rows:
[[40 35 48 42]
[45 50 47 49]]
after editing the slice, scores[0, 2] = 0Broadcasting ကို shape နဲ့ ဖတ်ခြင်း
Broadcasting (3, 4) with (4,) and (3, 1)
----------------------------------------
scores (3, 4) bonus (4,) -> treated as (1, 4)
[[40 35 48 42] [ 2 0 5 0] copied down 3 rows
[28 31 25 30] + [ 2 0 5 0]
[45 50 47 49]] [ 2 0 5 0]
scores (3, 4) row_offset (3, 1)
[[40 35 48 42] [[ 1] copied across 4 columns
[28 31 25 30] + [ 3]
[45 50 47 49]] [ 0]]
rule: compare shapes from the right; sizes must match or be 1Row တစ်ခုစီကို value တစ်ခုစီ ပေါင်းချင်တဲ့အခါ shape (3,) array ကို တိုက်ရိုက် ပေါင်းရင် 'operands could not be broadcast together' error ရပါတယ်။ arr[:, np.newaxis] ဒါမှမဟုတ် reshape(3, 1) နဲ့ column vector ပြောင်းပါ။ mean(axis=1, keepdims=True) လို reduction ကလည်း (3, 1) shape ကို တန်းပေးလို့ row တစ်ခုစီရဲ့ ပျမ်းမျှကို နှုတ်တဲ့ normalisation မှာ အသုံးဝင်ပါတယ်။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ NumPy
NumPy ကို တိုက်ရိုက် import မလုပ်ရင်တောင် data နဲ့ ပတ်သက်တဲ့ Python tool အများစုက သူ့ပေါ်မှာ တည်ဆောက်ထားပါတယ်။ pandas column တွေရဲ့ အောက်မှာ array တွေ ရှိပြီး scikit-learn က feature ဇယားကို 2D array အဖြစ် လက်ခံပါတယ်၊ image library တွေကလည်း ပုံတစ်ပုံကို (height, width, 3) shape ရှိတဲ့ array အဖြစ် ပြန်ပေးပါတယ်။
- Sensor ဒါမှမဟုတ် finance data: တစ်ရက်ကို row တစ်ခု ထားပြီး mean(axis=1) နဲ့ နေ့စဉ် ပျမ်းမျှ၊ boolean mask နဲ့ ကန့်သတ်ချက် ကျော်တဲ့ reading တွေကို ရှာပါတယ်။
- Machine learning preprocessing: column တစ်ခုစီကို (x - mean) / std နဲ့ standardize လုပ်ရာမှာ broadcasting ကို သုံးပြီး model ကို မထည့်ခင် dtype ကို float32 လို ပြောင်းလေ့ရှိပါတယ်။
- Image processing: ပုံတစ်ပုံ လုံးကို တောက်ပအောင် တစ်ကြောင်းတည်းနဲ့ ပေါင်းပြီး uint8 overflow မဖြစ်အောင် np.clip နဲ့ 0-255 အတွင်း ထိန်းပါတယ်။
အမှားများ
NumPy နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ
Slice ကို copy လို့ ထင်ခြင်း
first_col = data[:, 0] ပြီးနောက် first_col ကို ပြင်လိုက်ရင် data ပါ ပြောင်းသွားပါတယ်။ Function တစ်ခုထဲမှာ ဒီလို ပြင်မိရင် ခေါ်တဲ့သူရဲ့ data ကို တိတ်တဆိတ် ဖျက်ဆီးပစ်တတ်ပါတယ်။ သီးခြား ပြင်ချင်ရင် data[:, 0].copy() လို့ ရေးပါ။ Boolean mask နဲ့ fancy indexing ကတော့ copy ပြန်ပေးလို့ ပြဿနာ ပြောင်းပြန် ဖြစ်တတ်ပါတယ် — data[mask] ရဲ့ ရလဒ်ကို ပြင်လို့ data မပြောင်းပါဘူး၊ data[mask] = value လို တိုက်ရိုက် assign လုပ်မှ ပြောင်းပါတယ်။
axis ကို ပြောင်းပြန် သုံးခြင်း
ကျောင်းသားတစ်ယောက်ချင်းရဲ့ ပျမ်းမျှ လိုချင်ပြီး axis=0 လို့ ရေးမိရင် error မတက်ဘဲ quiz ပျမ်းမျှ ၄ ခုကို ရပါတယ်။ ရလဒ်ရဲ့ shape ကို စစ်ပါ — ကျောင်းသား ၃ ယောက်အတွက် value ၃ ခု ရသင့်ပါတယ်။
Broadcasting က shape မှားတာကို ဖုံးထားခြင်း
Shape (3,) နဲ့ (3, 1) ကို နှုတ်ရင် error မတက်ဘဲ (3, 3) ဇယားကြီး ထွက်လာပါတယ်။ Row တစ်ခုစီရဲ့ ပျမ်းမျှကို keepdims မပါဘဲ ယူပြီး ပြန်နှုတ်တာက ဒီ bug ကို ဖြစ်စေလေ့ရှိပါတယ်၊ ဒါကြောင့် အရေးကြီးတဲ့ နေရာတွေမှာ assert result.shape == expected ထည့်ပါ။
Best Practices
Best practices
- import numpy as np ကို convention အတိုင်း သုံးပြီး array အသစ်တိုင်းရဲ့ shape နဲ့ dtype ကို print ထုတ်စစ်ပါ။
- Array ကြီးတွေကို Python for loop နဲ့ cell တစ်ခုချင်း မပတ်ပါနဲ့၊ expression, reduction နဲ့ mask ကို ဦးစားပေးပါ။
- Float တွေကို == နဲ့ မနှိုင်းယှဉ်ဘဲ np.allclose ဒါမှမဟုတ် np.isclose ကို သုံးပါ။
- Random data လိုရင် rng = np.random.default_rng(seed) နဲ့ seed ပေးထားလို့ ရလဒ်ကို ပြန်ထုတ်နိုင်အောင် ထားပါ။
Mini challenge
Mini challenge: temperature sensor ဇယား
Sensor တစ်ခုက ၄ ရက်ကြာ တစ်ရက်ကို reading ၆ ခုစီ မှတ်ထားပါတယ်။ Loop မသုံးဘဲ NumPy expression တွေနဲ့ နေ့စဉ် အပူချိန် အတက်အကျ၊ column တစ်ခုစီကို standardize လုပ်ခြင်း၊ ပူလွန်းတဲ့ reading အရေအတွက်ကို တွက်ပါ။ နောက်ဆုံးမှာ mask နဲ့ in-place clip လုပ်ပြီး original data ကို backup copy နဲ့ ကာကွယ်ပါ။
- daily_range က row တစ်ခုစီအတွက် max - min ကို shape (4,) နဲ့ ပြန်ပေးရမယ်
- standardize_columns က keepdims=True ကို သုံးပြီး shape (4, 6) ကို ပြန်ပေးရမယ်
- hot_readings က boolean mask နဲ့ limit ကျော်တဲ့ reading အရေအတွက်ကို int အဖြစ် ပြန်ပေးရမယ်
- Clip မလုပ်ခင် .copy() နဲ့ backup ယူပြီး မူရင်း value ကို print ထုတ်ပြပါ
import numpy as np
# 4 days x 6 readings (degrees C)
temps = np.array([
[21.0, 22.5, 25.1, 27.8, 26.0, 23.2],
[19.5, 20.1, 24.0, 29.4, 28.8, 24.5],
[22.2, 23.0, 26.7, 31.2, 30.1, 25.9],
[18.9, 19.4, 21.8, 24.6, 23.7, 20.3],
])
def daily_range(t: np.ndarray) -> np.ndarray:
# TODO: max minus min along the right axis
...
def standardize_columns(t: np.ndarray) -> np.ndarray:
# TODO: (t - column mean) / column std, using keepdims=True
...
def hot_readings(t: np.ndarray, limit: float) -> int:
# TODO: count cells above limit with a mask
...
# TODO: print the results, then back up temps and clip values above 30 in placeရလဒ်: Daily range [6.8 9.9 9. 5.7]၊ z shape (4, 6)၊ hottest day index 2၊ 28 ကျော်တဲ့ reading 4 ခု၊ backup မှာ 31.2 ကျန်နေပြီး clip လုပ်ထားတဲ့ array မှာ 30.0 ဖြစ်သွားရပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
Row တစ်ခုစီအတွက် ရလဒ် တစ်ခုစီ လိုချင်ရင် axis=1 ပါ။ Column အလိုက် mean ကို keepdims=True နဲ့ ယူရင် shape (1, 6) ရလို့ (4, 6) နဲ့ broadcast ဖြစ်ပါတယ်။ (t > limit).sum() က True တွေကို ရေတွက်ပေးပါတယ်။
အဖြေ ကြည့်ရန်
import numpy as np
# 4 days x 6 readings (degrees C) from one sensor
temps = np.array([
[21.0, 22.5, 25.1, 27.8, 26.0, 23.2],
[19.5, 20.1, 24.0, 29.4, 28.8, 24.5],
[22.2, 23.0, 26.7, 31.2, 30.1, 25.9],
[18.9, 19.4, 21.8, 24.6, 23.7, 20.3],
], dtype=np.float64)
def daily_range(t: np.ndarray) -> np.ndarray:
"""Max minus min for every day (one value per row)."""
return t.max(axis=1) - t.min(axis=1)
def standardize_columns(t: np.ndarray) -> np.ndarray:
"""Z-score each reading slot so columns become comparable."""
mean = t.mean(axis=0, keepdims=True) # shape (1, 6)
std = t.std(axis=0, keepdims=True)
return (t - mean) / std # broadcasts (4, 6) with (1, 6)
def hot_readings(t: np.ndarray, limit: float) -> int:
return int((t > limit).sum())
print("daily range:", daily_range(temps).round(1))
z = standardize_columns(temps)
print("z shape:", z.shape)
print("column means after z-score:", np.abs(z.mean(axis=0)).max() < 1e-12)
print("hottest day index:", int(temps.max(axis=1).argmax()))
print("readings above 28:", hot_readings(temps, 28.0))
backup = temps.copy() # a real copy, not a view
temps[temps > 30] = 30 # clip in place with a mask
print("original kept in backup:", backup[2, 3], "clipped:", temps[2, 3])Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- NumPy array မှာ shape တစ်ခုနဲ့ dtype တစ်ခုပဲ ရှိပြီး operation တွေက cell တိုင်းကို တစ်ပြိုင်နက် တွက်ပါတယ်။
- axis က ချေဖျက်မယ့် dimension ကို ရွေးတာဖြစ်ပြီး ရလဒ် shape ကို အမြဲ စစ်ပါ။
- Broadcasting က shape တွေကို ညာဘက်ကနေ နှိုင်းယှဉ်ပြီး size တူရင် ဒါမှမဟုတ် 1 ဖြစ်ရင် ကိုက်ညီပါတယ်။
- Basic slice က view ဖြစ်ပြီး mask နဲ့ fancy indexing က copy ဖြစ်ပါတယ်၊ သီးခြားလိုရင် .copy() ကို သုံးပါ။
NumPy — Quickstart — NumPy