###### tags: `Python` `code` # 221218 Python聯課 --- ## Numpy 前情提要 [官方資料](https://numpy.org/) ### 小介紹 - Python的擴充程式庫 - **快速**處理矩陣運算&多維陣列 - 在本機執行要記得[下載](https://numpy.org/install/) ( 所以競賽、檢定不能用numpy喔 ) - 資料結構為ndarray (n-dimensional array) - 功能如下 ![](https://i.imgur.com/GSFUVS2.png) ## Numpy ### 建立array #### `np.array(seq)` 也可以從原本Python的list和tuple轉過來 ```python= import numpy as np a = np.array([5, 4, 3]) b = np.array((5, 4, 3)) print(a, type(a)) print(b, type(b)) ``` #### `np.zeros((x,y,...))` `np.ones((x,y,...))` 還記得上次說的**列**和**行**嗎 XD 請問這是幾乘幾的矩陣? ```python= alist = [[1, 2, 3], [4, 5, 6]] ``` 不太會看?沒關係,他擺起來像這樣 ``` 1 2 3 4 5 6 ``` 所以是幾乘幾呢? Ans. 2x3 我們可以用這3個function來初始化矩陣 ```python= import numpy as np # 資料全部為0 a = np.zeros((2, 3)) # 資料全部為1 b = np.ones((2, 3)) c = np.full((2, 3), 8) print(a) print(b) print(c) ``` 第一層axis(軸)有兩個資料,第二層axis有三個 要取資料:用index 在剛剛的程式底下加上這個 ```python= print(a[0]) print(a[0][1]) ``` 再加上這三行,我們來看看預設資料型態的部分 ```python= print(type(a[0][0])) print(type(b[0][0])) print(type(c[0][0])) ``` 如果一開始就要`int`型態的話,可以這樣設定 ```python= import numpy as np # 資料全部為0 a = np.zeros((2, 3), dtype=np.int64) # 資料全部為1 b = np.ones((2, 3), dtype=np.int32) c = np.full((2, 3), 8) print(a) print(b) print(c) print(type(a[0][0])) print(type(b[0][0])) print(type(c[0][0])) ``` `int32` 和 `int64` 是記憶體空間 #### `np.arange(start, stop, step)` ```python= import numpy as np # 0~ a = np.arange(5) print(a, type(a)) ``` `np.arange(x)` 類似 `range(x)` 的功效,會以 `numpy.ndarray` 的型態回傳,那他當然有這個功能 ```python= import numpy as np # 2 ~ 49且以3為間隔 a = np.arange(2, 50, 3) print(a) ``` 偷偷來測試一下速度 ```python= import time as t import numpy as np alist = [] t1 = t.time() for i in range(10000): alist.append(i) t2 = t.time() aarray = np.arange(10000) t3 = t.time() print(t2-t1, t3-t2) ``` #### `np.eye(x)` 還記得上一節課講的單位矩陣嗎 ```python= import numpy as np # 生成2x2的單位矩陣 a = np.eye(2) print(a) ``` #### `np.reshape()` 檢查方式:數字積 = 原本矩陣元素個數 ```python= import numpy as np a = np.arange(12) b = a.reshape(6, 2) c = a.reshape(2, 3, 2) print('a') print(a) print('\nb') print(b) print('\nc') print(c) ``` #### 隨機產生 和random套件的用法類似 上次沒講到`random.random()` 它會返回 `[0, 1)` 之間的實數 ```python= import numpy as np # random(size) a = np.random.random((2, 3)) # randint(start, stop, size) b = np.random.randint(1, 1000, (2, 3)) print(a) print(b) ``` #### `np.linspace(x, y, d)` ```python= import numpy as np # 從1~5產生三個平均分散的數字 (含1, 5) a = np.linspace(1, 5, 3) print(a) ``` #### 排序 ```python= import numpy as np a = np.random.randint(1, 10, (5)) print(a) # 排序 a = np.sort(a) print(a) ``` 其實很多功能是可以自己去查來玩玩看的! 畢竟函式太多了講不完 ### 讓我們進入二維 #### 取得基本數據 相信大家看完範例就能懂功能了 - `arr.ndim`:返回有幾個維度 (axis) - `arr.size`:返回總共多少元素 - `arr.shape`:以tuple的形式返回每個axis的長度 ```python= import numpy as np a = np.arange(12) b = a.reshape(6, 2) print('a') print(a) print(a.ndim) print(a.shape) print(a.size) print('\nb') print(b) print(b.ndim) print(b.shape) print(b.size) ``` #### 新增維度 ```python= import numpy as np a = np.arange(12) print(a) print(a.shape) b = a[np.newaxis, :] print(b) print(b.shape) c = a[:, np.newaxis] print(c) print(c.shape) ``` ### 數學 #### 三角函數 參數記得用弧度制 ```python= import numpy as np a = np.array([0, np.pi/6, np.pi/2]) s = np.sin(a) print(s) c = np.cos(a) print(c) # 還可以結合linspace()產生數據點 b = np.linspace(1, 10, 1000) sin = np.sin(b) print(sin) ``` #### 向量 內積 ```python= import numpy as np a = np.array([5, 4]) b = np.array([3, 1]) print(a.dot(b)) ``` #### 解方程式 我們用同樣的二元一次方程式來試試看 ![](https://i.imgur.com/ZT4DUSz.jpg) ```python= import numpy as np A = np.array([[3, 1], [2, -7]]) B = np.array([10, -1]) print(np.linalg.solve(A, B)) ``` #### 練習題 不能用 `solve`,自己去查查看矩陣相關操作 用上面給的操作順序試著完成一樣的功能 提示:`inverse` `dot` ```python= import numpy as np A = np.array([[3, 1], [2, -7]]) B = np.array([10, -1]) A_inv = np.linalg.inv(A) print(A_inv) print(A_inv.dot(B)) print(np.linalg.solve(A, B)) ``` ## Matplotlib [官方資料](https://matplotlib.org/stable/index.html) ### 小介紹 - Python中的套件 - 可將數據視覺化 - 一樣,若在本機用要事先下載 - 在`replit`中,他會先偵測你用到的套件,然後自己去安裝 ![](https://i.imgur.com/RprSNkh.png) - 裝好之後執行,`console`那裏會多一個`output`,就像`turtle`那樣 ### 描點 #### 結合剛剛`numpy`的`linspace` ```python= # import需要用到的套件 import numpy as np import matplotlib.pyplot as plt # 產生資料 x = np.linspace(1, 10, 1000) plt.plot(x) plt.show() ``` ```python= # import需要用到的套件 import numpy as np import matplotlib.pyplot as plt # 產生資料 x = np.linspace(1, 10, 1000) sin = np.sin(x) plt.plot(x, sin) plt.show() ``` #### 也可以用描點的 ```python= # import需要用到的套件 import numpy as np import matplotlib.pyplot as plt # 產生資料 x = np.linspace(1, 10, 100) sin = np.sin(x) plt.plot(x, sin, 'o') plt.show() ``` #### 還可以畫線+描點 ```python= import numpy as np import matplotlib.pyplot as plt x = np.linspace(1, 10, 100) sin = np.sin(x) plt.plot(x, sin, marker='o') plt.show() ``` #### 變顏色&樣式 linewidth ```python= plt.plot(x, sin, linewidth=2) ``` labels ```python= import numpy as np import matplotlib.pyplot as plt x = np.linspace(1, 10, 4) y = np.random.randint(1, 100, (4)) labels = np.array(['Tinky Winky', 'Dipsy', 'Po', 'Laa-Laa']) plt.plot(x, y, linewidth=2) plt.xticks(x, labels, rotation ='vertical') plt.show() ``` [color](https://matplotlib.org/stable/gallery/color/named_colors.html) ```python= import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 100) plt.plot(x, 'orange') plt.show() ``` #### 練習題 - `y = x**2` - x用`linspace` (100 data) - linewidth (2) - color ### [Others](https://matplotlib.org/stable/plot_types/index.html) #### [Scatter](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html) ```python= import numpy as np import matplotlib.pyplot as plt en = np.random.randint(1, 100, (100)) math = np.random.randint(1, 100, (100)) # 2 axis plt.scatter(en, math, linewidth=2) plt.show() ``` #### [Bar](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html) ```python= import numpy as np import matplotlib.pyplot as plt x = np.linspace(1, 10, 4) y = np.random.randint(1, 100, (4)) labels = np.array(['Tinky Winky', 'Dipsy', 'Po', 'Laa-Laa']) plt.bar(x, y, linewidth=2) plt.xticks(x, labels, rotation ='vertical') plt.show() ``` #### [Reference for Matplotlib artists](https://matplotlib.org/stable/gallery/shapes_and_collections/artist_reference.html#sphx-glr-gallery-shapes-and-collections-artist-reference-py) ## [Web](https://hackmd.io/mYHiarVQSmiG0bbhMCqBSQ) - flask ### structure - main.py - **template** - base.html - **home.html** - xx.html - xx.jinja2 - **static** - **main.css** - bootstrap - xx.css - xx.js ### `main.py` ```python= import os from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') app.run(host='0.0.0.0', port=81) ``` ### `home.html` ```html= <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/static/main.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins&display=optional"> <title>hi</title> </head> <body> </body> <footer></footer> </html> ``` ### `main.css` ```css= @import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap'); body, button, html, input, select, textarea { font-family: "Microsoft JhengHei", 'Poppins', sans-serif; } body { background-color: #010827; color: #D9EEFD; width: 80%; margin: auto; } h1 { color: #FFC600; } p { font-size: 20px; } p a{ color: #FAF7AF; } ```