Thuta Learning
ရှာဖွေရန်
AdvancedData & Databasesintermediate

Broadcasting

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Broadcasting ဆိုတာ shape မတူတဲ့ array တွေကို NumPy က စည်းမျဉ်းအချို့အရ ကိုက်ညီအောင်တွက်ပေးတဲ့ mechanism ပါ။ ဥပမာ table တစ်ခုရဲ့ row တိုင်းကို tax rate တူတူထပ်ပေါင်းတာ၊ column တစ်ခုချင်းစီကို different scale နဲ့မြှောက်တာမျိုးမှာ loop မရေးဘဲတွက်နိုင်ပါတယ်။

python
import numpy as np

# 2 rows x 3 columns
sales = np.array([
    [100, 200, 300],
    [400, 500, 600]
])

# 3 values: one value for each column
bonus = np.array([10, 20, 30])

final_sales = sales + bonus
print(final_sales)

sales က shape (2, 3) ဖြစ်ပြီး bonus က shape (3,) ဖြစ်ပါတယ်။ NumPy က bonus ကို row တစ်ခုချင်းစီအတွက် တူတူသက်ရောက်စေပြီး column အလိုက်ပေါင်းပေးပါတယ်။

You should see
[[110 220 330] [410 520 630]]

Info

Broadcasting က magic လိုမြင်ရပေမယ့် rule ရှိပါတယ်။ နောက်ဆုံး dimension တွေက တူရမယ်၊ ဒါမှမဟုတ် dimension တစ်ခုက 1 ဖြစ်ရမယ်။ မကိုက်ရင် shape error တက်ပါမယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Shape မကိုက်တဲ့ array တွေကို အတင်းပေါင်းရင် ValueError: operands could not be broadcast together ဖြစ်နိုင်ပါတယ်။ Error တက်ရင် .shape ကို အရင် print ထုတ်ကြည့်ပါ။

လေ့ကျင့်ခန်း

Product category တစ်ခုချင်းစီကို discount rate မတူဘဲသတ်မှတ်ချင်ရင် broadcasting နဲ့ row တိုင်းပေါ် column-wise discount သက်ရောက်စေနိုင်ပါတယ်။

python
import numpy as np

prices = np.array([
    [1000, 1500, 2000],
    [1200, 1800, 2400]
])

discount_rate = np.array([0.95, 0.90, 0.85])
discounted_prices = prices * discount_rate

print(discounted_prices)

You'll know it worked when: [[ 950. 1350. 1700.] [1140. 1620. 2040.]]

Broadcasting | Thuta Learning