2022年1月4日 星期二
NumPy 教程
NumPy 是什麼
首先,什麼是Numpy?
Numpy 是 Python 的一個重要模組(Python 是一個高階語言,可以透過整合其他低階語言同時擁有效能和高效率的開發),主要用於資料處理上。
Python 處理龐大資料時,其原生 list 效能表現並不理想(但可以動態存異質資料),而 Numpy 具備平行處理的能力,可以將操作動作一次套用在大型陣列上。
此外 Python 其餘重量級的資料科學相關套件(例如:Pandas、SciPy、Scikit-learn 等)都幾乎是奠基在 Numpy 的基礎上。因此學會 Numpy 對於往後學習其他資料科學相關套件打好堅實的基礎。
Numpy 基礎操作
import numpy as np
1. array應用
np.array(): 有矩陣加減乘除的應用
np.zeros( (x,y) ): x*y全零矩陣
np.empty(): 用法與np.zeros一樣,但唯一的差別是NumPy不會初始化陣列內元素的初始值,所以內容將會是不確定的。
np.arange( 起始值, 結束值, 步幅, 資料型別 )
np.linspace( 起始值, 結束值, 起始與結束的區間內要產生幾個元素 )
2. np取值
np.sum:矩陣加總
np.min:矩陣最小值
np.max:矩陣最大值
np.mean:矩陣平均值
np.sqrt:矩陣內所有元素開平方根
np.exp:矩陣內所有元素進行Exponential function(e)運算
np.add:矩陣或陣列相加
3. np slicing
- Indexing
索引(Indexing)的用途不外乎就是為了要從陣列和矩陣中取值,但除此之外有很多種功能!
可以取出連續區間,還可以間隔取值!
選取連續區間 [a:b]
2. slicing
切片(Slicing)的用途和索引(Indexing)很像!
若能活用便能加快程式撰寫速度!
間隔選取[::c]
以1維陣列來說明x[a:b:c]
a:選取資料的起始索引
b:選取資料的結束索引+1
c:選取資料間隔,以索引值可以被此值整除的元素,不指定表示1
3. 迭代
迭代(Iterating)比較熟悉一點,可以說就像foreach一樣的使用方法
# Iteracted overa = np.arange(10) ** 2for i in a:print(“a**(1/2)=> {0}”.format(np.round(i**(1/2), 0)))
4. Shape變化
np.reshape(a, b):這是最基本的塑形功能,可以直接將陣列重新塑形成a-by-b或是更高維度的形狀!
np.ravel():此功能會回傳一個將陣列或矩陣經扁平化(flattened)處理後的陣列
ndarray.T:轉置矩陣(transpose)
5. 矩陣堆疊(Stacking)
這功能可以方便運算時矩陣串接的需求!
np.vstack(a, b):將a, b矩陣沿著垂直軸堆疊!
np.hstack(a, b):將a, b矩陣沿著水平軸堆疊!
a = np.arange(1,11).reshape(2,5)
print(“a=>\n{0}”.format(a))print()# 水平堆疊print(“np.vstack((a,a))=>\n{0}”.format(np.hstack((a,a))))print()# 垂直堆疊print(“np.hstack((a,a))=>\n{0}”.format(np.vstack((a,a))))
#本篇只簡單介紹numpy較常用到的指令
NumPy is the fundamental package for scientific computing with Python.
- Website: https://www.numpy.org
- Documentation: https://numpy.org/doc
- Mailing list: https://mail.python.org/mailman/listinfo/numpy-discussion
- Source code: https://github.com/numpy/numpy
- Contributing: https://www.numpy.org/devdocs/dev/index.html
- Bug reports: https://github.com/numpy/numpy/issues
- Report a security vulnerability: https://tidelift.com/docs/security
It provides:
- a powerful N-dimensional array object
- sophisticated (broadcasting) functions
- tools for integrating C/C++ and Fortran code
- useful linear algebra, Fourier transform, and random number capabilities
Testing:
NumPy requires pytest and hypothesis. Tests can then be run after installation with:
python -c 'import numpy; numpy.test()'
Code of Conduct
NumPy is a community-driven open source project developed by a diverse group of contributors. The NumPy leadership has made a strong commitment to creating an open, inclusive, and positive community. Please read the NumPy Code of Conduct for guidance on how to interact with others in a way that makes our community thrive.
Call for Contributions
The NumPy project welcomes your expertise and enthusiasm!
Small improvements or fixes are always appreciated; issues labeled as "good first issue" may be a good starting point. If you are considering larger contributions to the source code, please contact us through the mailing list first.
Writing code isn’t the only way to contribute to NumPy. You can also:
- review pull requests
- triage issues
- develop tutorials, presentations, and other educational materials
- maintain and improve our website
- develop graphic design for our brand assets and promotional materials
- translate website content
- help with outreach and onboard new contributors
- write grant proposals and help with other fundraising efforts
If you’re unsure where to start or how your skills fit in, reach out! You can ask on the mailing list or here, on GitHub, by opening a new issue or leaving a comment on a relevant issue that is already open.
Our preferred channels of communication are all public, but if you’d like to speak to us in private first, contact our community coordinators at numpy-team@googlegroups.com or on Slack (write numpy-team@googlegroups.com for an invitation).
We also have a biweekly community call, details of which are announced on the mailing list. You are very welcome to join.
If you are new to contributing to open source, this guide helps explain why, what, and how to successfully get involved.
NumPy介紹
什麼是 NumPy?
NumPy 是一個用於處理數組的 Python 庫。
它還具有用於線性代數、傅立葉變換和矩陣領域的功能。
NumPy 由 Travis Oliphant 於 2005 年創建。它是一個開源項目,您可以自由使用它。
NumPy 代表數值 Python。
為什麼要使用 NumPy?
在 Python 中,我們有用於數組目的的列表,但它們的處理速度很慢。
NumPy 旨在提供比傳統 Python 列表快 50 倍的數組對象。
NumPy 中的數組對象稱為ndarray,它提供了許多支持功能,使使用起來 ndarray非常容易。
數組在數據科學中使用非常頻繁,其中速度和資源非常重要。
數據科學:是計算機科學的一個分支,我們研究如何存儲、使用和分析數據以從中獲取信息。
為什麼 NumPy 比列表快?
與列表不同,NumPy 數組存儲在內存中的一個連續位置,因此進程可以非常有效地訪問和操作它們。
這種行為在計算機科學中被稱為引用的局部性。
這是 NumPy 比列表更快的主要原因。此外,它還針對最新的 CPU 架構進行了優化。
NumPy 是用哪種語言編寫的?
NumPy 是一個 Python 庫,部分是用 Python 編寫的,但大部分需要快速計算的部分是用 C 或 C++ 編寫的。
NumPy 代碼庫在哪裡?
NumPy 的源代碼位於此 github 存儲庫 https://github.com/numpy/numpy
github:使許多人能夠在同一個代碼庫上工作。
Numpy 入門 – Numpy是什麼?
Numpy 入門 – Numpy是什麼?
應用篇Numpy是什麼?
在數據分析或是計算與統計時,我們通常會處理大規模的數據。這種時候我們就會需要多次元的演算。
Python跟Java以及C語言相比,compile的速度雖然比較慢。但是只要運用Numpy的「ndarray」的話就可以快速的處理數據。
另外,在使用matplotlib,Pandas等等的Library時也經常會使用到Numpy。
今天要來介紹Numpy的安裝方式以及Numpy的行列的使用方法。
Numpy的安裝與import。
Numpy可以直接利用pip來安裝。另外我們因為已經安裝了anaconda,所以可以直接輸入下面的命令來安裝Numpy。
pip install numpy通常在import numpy時我們會把名稱取為np。例如,在製作3行3列的行列時的代碼會像下面這樣。
import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(x)
#輸出結果
#[[1 2 3]
# [4 5 6]
# [7 8 9]]import numpy as np的意思就是把numpy省略成np,在寫程式上會比較方便。
另外雖然聽到行列大家會聯想到matrix,不過在numpy中大家比較常使用array,因此以後在numpy的相關文章中如果提到行列,基本上都是在講array。
為什麼要用 Numpy?
只用Python不好嗎?
前言
這是我學習 Deep Learning Specialization 系列課程的心得筆記,其他相關的心得我會陸續整理在 學習深度學習的課堂筆記 底下
正文


在開始學習Machine Learning 之前我就是一個Python的重度使用者,開始學習ML之後我才接觸到Jupyter notebook跟Numpy這兩項工具。一開始有些不習慣,但久了之後覺得這個組合實在是非常方便。不過有一個問題一直令我非常不理解…
為什麼做資料分析的人都不喜歡寫 for loop?
Numpy在做數學(向量,矩陣)運算上提供了非常多方便的語法,例如向量的內積,如果要自己用for loop來做會很麻煩:
VEC_LENGTH = 100000
w = np.random.rand(VEC_LENGTH)
x = np.random.rand(VEC_LENGTH)# for loop
c = 0
for i in range(VEC_LENGTH):
c += w[i] * x[i]# numpy
import numpy as np
c = np.dot(w, x)
numpy版本是不是簡單又清楚呢?除了向量內積以外,許多常用的運算也有很好的支援,例如矩陣乘法
A = np.array([
[1, 2, 3],
[2, 3, 4],
])B = np.array([
[2],
[0],
])A * B
# array([[2 4 6], [0 0 0]])
或是對矩陣內的每一個項目進行操作
A = np.array([1, 2, 3])
A ** 2
# array([1, 4, 9])但除了這些 API簡單好用之外,使用Numpy跟自己寫的for loop有一個最關鍵的差別,那就是執行的效能!!我在Jupyter notebook上面做了簡單的實驗,結果如下:
VEC_LENGTH = 100000
w = np.random.rand(VEC_LENGTH)
x = np.random.rand(VEC_LENGTH)
tic = time.time()
c = 0
for i in range(VEC_LENGTH):
c += w[i] * x[i]
toc = time.time()
print('For loop took: %s ms' % str(1000 * (toc - tic)))# >> For loop took: 124.56703186 mstic = time.time()
c = np.dot(w, x)
toc = time.time()
print('Vectorized dot took: %s ms' % str(1000 * (toc - tic)))# >> Vectorized dot took: 0.262975692749 ms
124.5670 ms vs 0.2529ms !!快要五百倍的速度提升,五百倍!!這樣的速度提升在其他Numpy API 也都有類似的情形(可以參考這個Notebook)。
這揪~竟~是為什麼呢??
原來Numpy除了幫我們把結果正確算出來之外,會透過硬體裝置(GPU or CPU)來進行加速運算。因此當我們把原本要交給同一個CPU的運算改成透過GPU上面好多個運算單元來同時進行就可以達到這樣的效果了 💪 💪
另外值得一提的是就算電腦沒有安裝GPU,Numpy 還是可以透過SIMD (Single Instruction, Multiple Data) 這種CPU內建的機制來達成加速,因此不論如何使用Numpy就是比自己寫 for loop快上許多。


結論
對於認真想把是資料處理當飯吃的人來說,五百倍的加速是跑一小時得到結果跟一個月的差別… 如果沒有特別注意很容易就不小心在程式碼裡面寫了低效能的Code而不自知 🙁 所以要非常小心。
最簡單無腦的原則就是:
除非萬不得已,不然不要用 for loop來做資料處理。
以上就是這部分的心得。謝謝您閱讀到最後。想看更多我上課的心得可以參考我學習深度學習的課堂筆記
-
Python/第一次用就上手 - Python Taiwan Wiki 登入 搜尋: Python / 第一次用就上手 最新更動 尋找頁面 PotWiki/慣...
-
Python 教學 Python 教學共有 190 多篇 Python 教學,包含基本語法、函式庫、網路爬蟲和一系列由淺入深的精選範例,不僅能對 Python 有充分的認識,還能透過 Python 做出各種有趣的應用! 點選 左側選單 可以查看所有文章 ( 行動裝置可點選 ...
-
NumPy 教程 NumPy(Numerical Python) 是 Python 語言的一個擴展程序庫,支持大量的維度數組與矩陣運算,此外也針對數組運算提供大量的數學函數庫。 NumPy 的前身 Numeric 最早是由 Jim Hugunin 與其它協作者共同開發,200...