Thuta Learning
Numpy
AdvancedData & Databasesintermediate

Reshaping Arrays

reshape() က array ရဲ့ shape ကိုပြောင်းပေးပါတယ်။ Data element အရေအတွက်တော့ မပြောင်းပါဘူး။ ဥပမာ element 9 ခုရှိတဲ့ 1-D array ကို 3x3 matrix ပြောင်းလို့ရပါတယ်။ ဒါပေမယ့် element 9 ခုကို 2x5 လုပ်မယ်ဆိုရင် 10 နေရာလိုတာကြောင့် error ဖြစ်ပါမယ်။

python
import numpy as np

numbers = np.arange(1, 10)
print("Original:", numbers)
print("Original shape:", numbers.shape)

matrix = numbers.reshape((3, 3))
print("
3x3 matrix:
", matrix)

flattened = matrix.reshape(-1)
print("
Back to 1-D:", flattened)

np.arange(1, 10) က 1 ကနေ 9 အထိ element 9 ခုထုတ်ပေးပါတယ်။ reshape((3, 3)) က row 3 ခု၊ column 3 ခုအဖြစ်ပြောင်းပါတယ်။ reshape(-1) က NumPy ကို “လိုအပ်တဲ့ size ကို ကိုယ့်ဘာသာတွက်ပြီး 1-D ပြန်လုပ်ပါ” လို့ပြောတာပါ။

You should see
Original: [1 2 3 4 5 6 7 8 9] Original shape: (9,) 3x3 matrix: [[1 2 3] [4 5 6] [7 8 9]] Back to 1-D: [1 2 3 4 5 6 7 8 9]

Info

-1 ကို reshape မှာတစ်နေရာတည်းသာသုံးသင့်ပါတယ်။ NumPy ကကျန်တဲ့ dimension တွေကနေ missing dimension ကိုတွက်ပေးပါတယ်။

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

  • reshape လုပ်မယ့် shape ထဲက total slots နဲ့ array ထဲက element အရေအတွက် တူရပါမယ်။ မတူရင် reshape မရပါ။

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

Image data, ML training data တွေမှာ shape ပြောင်းရတာများပါတယ်။ ဥပမာ image pixels ကို flat vector ပြောင်းတာ၊ row data ကို table format ပြန်ပြောင်းတာမျိုးပါ။

You'll know it worked when:

Reshaping Arrays | Thuta Learning