嗨,今天來到鐵人的16天了,今天要說明一下在Numpy中很好用的廣播功能與會用到的函數。
若是想看其他Numpy的介紹:
首先!一定要先 import numpy !
import numpy as np
我們在之前提過如何產生(宣告)ndarray:
a = np.array([1,2,3])
b = np.array([2,2,2])
現在我們要將a和b相乘:
a * b
會得到:
array([2, 4, 6])
這是沒有問題的。
NumPy is smart enough to use the original scalar value without actually making copies, so that broadcasting operations are as memory and computationally efficient as possible
廣播的使用原來的向量而不需要實際的複製,所以它可以有效的運用記憶體和運算,不懂的話直接來試試看下面的範例:
c = np.array([1.0, 2.0, 3.0])
d = 2
c * d
上面這個一樣會得到 array([ 2., 4., 6.]),這就是所謂的廣播!
相當於d也是一個array,可以想像是Numpy會把d給放大變成和c一樣的大小(shape),而不需要自己去複製和c一樣多個2。
這樣對廣播有概念了吧!
再來進階一點,這邊可能需要一點線性代數的概念:
x = np.arange(4)
上面這邊建立一個了一個 x = [0,1,2,3]
x2 = x.reshape(4,1)
我們用.reshape()將x的矩陣形狀改成4 X 1
y = np.ones(5)
接著建立一個y = [1,1,1,1]
接著將xx和y相加:
xx + y

我們可以想像xx + y的時候xx會延伸成:
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
而y:
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
所以兩個相加會變成
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
那這就是所謂的廣播!
接下來說明一下會用到的方法函數,先來看看reshape()吧:
Gives a new shape to an array without changing its data.
簡單來說reshape()就是用來改變array的shape,但並不會改變它的數值。
s = np.arange(6)
建立一個s = [0,1,2,3,4,5],接著將s做reshape()
s = s.reshape((3, 2))
s就會變成3 X 2了,如圖:
x = np.zeros((10, 2))
上面這個是建立一個都是0的矩陣,矩陣形狀為 10 X 2
y = x.T
T這個是將x整個選轉變成2 X 10,如圖:
再看一個例子:
x = np.array([[3,4],[5,6]])
將x做transpose:
x.T

看出差別了吧!
Base object if memory is from some other object.
我們直接來看一下範例就知道這是什麼了!
y = np.array([1,2,3,4])
y.base is None
會得到 True,是因為它的基底不是從其他的數值來的,來看看我們最前面的範例:
x = np.arange(4)
xx = x.reshape(4,1)
y = np.ones(5)
(xx + y)
xx.base is x
在上面第二行,將x.reshape(4,1)得到的結果給了xx,這表示xx是從x來的,所以True
來看看y呢?
x = np.arange(4)
xx = x.reshape(4,1)
y = np.ones(5)
(xx + y)
xx.base is y
會得到False,如圖:
這樣可以看出差別了嗎?
今天說明了廣播的特性,以及其他會用到的方法reshape、T以及base。
參考資料:
numpy.reshape
numpy.ndarray.T
numpy.ndarray.base
大大請教一下假設讀EXCEL資料不用array來做reshape要怎弄,還有假設要複製是不是用.copy()就好還是要怎樣?謝謝觀看及回覆