1. 導學
- 如何使用算法
- 如何評價算法的好壞
- 如何解決過擬合和欠擬合
- 如何調節算法的參數
- 如何驗證算法的正確性
1.1 要求
1.2 如何使用算法
- 如何評價算法的好壞
- 如何解決過擬合和欠擬合
- 如何調節算法的參數
- 如何驗證算法的正確性
2. 機器學習的數據
2.1 樣本

2.2 特征

2.3 特征空間


3. 機器學習分類
3.1 監督學習
給機器的訓練數據擁有 “標記” 或者 “答案”
- k近鄰
- 線性回歸和多項式回歸
- 邏輯回歸
- SVM
- 決策樹和隨機森林
3.2 非監督學習
給機器的訓練數據沒有任何“標記” 或者 “答案”
對沒有“標記”的數據進行分類--聚類分析
意義:
- 對數據進行降維處理
- 特征提取: 信用卡的信用評級 和 人的胖瘦無關?
- 特征壓縮: PCA (不損失數據的情況下,將高維數據壓縮成低維數據)
- 降維處理的意義:方便可視化
- 異常檢測:
3.3 半監督學習
給機器的訓練數據沒有任何“標記” 或者 “答案”
對沒有“標記”的數據進行分類---聚類分析
意義:
- 對數據進行降維處理
- 特征提取: 信用卡的信用評級 和 人的胖瘦無關?
- 特征壓縮: PCA (不損失數據的情況下,將高維數據壓縮成低維數據)
- 降維處理的意義:方便可視化
- 異常檢測:

3.4 增強學習
- 無人駕駛
- 機器人

4. 機器學習的其他分類
4.1 在線學習和批量學習(離線學習)
- 批量學習 Batch Learning(離線學習, 為主)
優點: 簡單
問題:如何適應環境變化
- 解決方案:定時重新批量學習
缺點:每次重新批量學習,運算量巨大;

- 在線學習Online Learning
優點:及時反映新的環境變化
問題:新的數據帶來不會的變化
- 解決方案:需要加強對數據進行監控
其他:也適用於數據量巨大,完全無法批量學習的環境

4.2 參數學習和非參數學習
- 參數學習 Parametric Learning
一旦學到參數,就不再需要原有的數據集
- 非參數學習 Nonparametric Learning
- 不對模型進行過多假設
- 非參數不等於沒參數
5. 監督學習任務
5.1 分類任務
- 二分類
- 判斷郵件是否為垃圾郵件
- 判斷發給客戶信用卡是否有風險
- 判斷病患是良性腫瘤;惡性腫瘤
- 判斷股票漲跌
- 多分類
- 手寫數字識別
- 圖像識別
- 判斷發給客戶信用卡的風險評級
- 2048游戲:轉換為多分類,是否上移動,下移,左移等
- 圍棋
- 無人車:根據環境信息,設置方向盤,油門、剎車
- 多分類的任務可以轉換成二分類任務
- 多標簽分類
一個圖片分到多個類別

5.2 回歸任務
- 結果是一個連續的數字的值,而非一個類別
- 房屋預測
- 市場分析
- 學生成績
- 股票價格
- 一般情況下,回歸任務可以簡化成分類任務
- 無人駕駛
5.3 工作流程

6. jupyter notebook
6.1 快捷鍵
run cell: ctrl + enter
change cell to md: m
change cell to code: c
delete cell: x
line number: L
6.2 魔法命令
- %run:在 jupyter 中加載 .py文件代碼
%run ./magic.py # ./為文件路徑
[out1]: hello('python')
import MagicTest.FirstML # 導入magictest的模塊
MagicTest.FirstML.predict(1)
[out2]: predict: ?
from MagicTest import FirstML
FirstML.predict(2)
[out3]: predict: ?
- %timeit: 測試代碼性能
%timeit L = [i**2 for i in range(1000)]
[out1]: 535 µs ± 11.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit L = [i**2 for i in range(10000000)]
[out1]: 5.89 s ± 923 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
L = []
for n in range(1000):
L.append(n ** 2)
[out]: 603 µs ± 16.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
- %time: 代碼計時(不用重復)
%time L = [i**2 for i in range(1000)]
[out1]: Wall time: 1e+03 µs
%%time
L = []
for i in range(1000):
L.append(i**2)
[out2]: Wall time: 2 ms
- 其他魔法命令
%lsmagic
[out1]:
Available line magics:
%alias %alias_magic %autoawait %autocall %automagic %autosave %bookmark %cd %clear %cls %colors %conda %config %connect_info %copy %ddir %debug %dhist %dirs %doctest_mode %echo %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %macro %magic %matplotlib %mkdir %more %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %ren %rep %rerun %reset %reset_selective %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode
Available cell magics:
%%! %%HTML %%SVG %%bash %%capture %%cmd %%debug %%file %%html %%javascript %%js %%latex %%markdown %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile
Automagic is ON, % prefix IS NOT needed for line magics.
%run? # 查看文檔
7. numpy和matplotlib
7.1 Numpy
7.11 Numpy.array
- 使用一:
import numpy as np
L = [i for i in range(10)]
print(L)
L[5] = 'Machine Learning'
print(L)
import array
arr = array.array('i', [i for i in range(10)]) # 只能定義一種類型
print(arr)
arr[5] = 100
print(arr)
nparr = np.array([i for i in range(10)]) # 只能定義一種類型
print(nparr)
print(nparr.dtype)
nparr = np.array([1, 2, 3.0]) # float
print(nparr.dtype)
[out1]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 'Machine Learning', 6, 7, 8, 9]
array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
array('i', [0, 1, 2, 3, 4, 100, 6, 7, 8, 9])
[0 1 2 3 4 5 6 7 8 9]
int32
float64
- 使用二:
# 全為0,默認浮點型
print('=================np.zero===================')
print(np.zeros(10))
print(np.zeros(10).dtype)
print(np.zeros(10, dtype=int))
print(np.zeros(shape=(3, 5), dtype=int))
print('=================np.ones===================')
# 全為1,默認浮點型
print(np.ones(10)) # 向量
print(np.ones( (3, 5) )) # 矩陣
print('=================np.full=================')
# 指定值
print(np.full(shape=(3, 5), fill_value=666)) # 為指定類型
print(np.full(shape=(3, 5), fill_value=666.0))
print('=================np.full=================')
# arange
print(np.arange(0, 1, 0.2)) # 可以有浮點數
# linspace
print('=================np.linspace===================')
print(np.linspace(0, 20, 10)) # [0,20]區間,生成10個等差數列
# random
print('=================np.random===================')
np.random.seed(100)
print(np.random.randint(0, 1, 10)) # [0, 1), 不包含1
print(np.random.randint(4, 8, size=(3, 5)))
print(np.random.randint(4, 8, size=10))
# 生成10個0-1之間均勻的浮點數
print(np.random.random(10))
# 正態分布
print(np.random.normal())
print(np.random.normal(10, 100)) # [10, 100)
print(np.random.normal(0, 1, (3, 5)))
[out1]:
=================np.zero===================
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
float64
[0 0 0 0 0 0 0 0 0 0]
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]
=================np.ones===================
[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.]]
=================np.full=================
[[666 666 666 666 666]
[666 666 666 666 666]
[666 666 666 666 666]]
[[666. 666. 666. 666. 666.]
[666. 666. 666. 666. 666.]
[666. 666. 666. 666. 666.]]
=================np.full=================
[0. 0.2 0.4 0.6 0.8]
=================np.linspace===================
[ 0. 2.22222222 4.44444444 6.66666667 8.88888889 11.11111111
13.33333333 15.55555556 17.77777778 20. ]
=================np.random===================
[0 0 0 0 0 0 0 0 0 0]
[[4 4 7 7 7]
[7 4 6 6 4]
[6 5 6 6 6]]
[6 5 4 4 7 4 7 4 6 4]
[0.56229626 0.00581719 0.30742321 0.95018431 0.12665424 0.07898787
0.31135313 0.63238359 0.69935892 0.64196495]
-0.23028508500632336
58.09241158682933
[[-1.26691058 0.27100509 2.14076322 0.47536904 0.24652489]
[-1.08417396 -2.3815826 -0.4363488 -2.07241186 -1.29543984]
[-0.46402358 -0.05702664 0.27592974 1.49451522 0.56682064]]
- 查詢相應文檔
np.random?
help(np.random.normal)
7.12 numpy基本操作
import numpy as np
x = np.arange(10)
print('x: ', x)
# 轉換 維度
X = np.arange(15).reshape(3, 5)
print('X:', X)
# 基本屬性
print('x維度:', x.ndim) # 查看維度屬性
print('X維度:', X.ndim)
print('X.shape: ', X.shape)
print('X.size: ', X.size)
# numpy.array的數據訪問
print('X:', X)
print('X[0][0]: (不推薦)', X[0][0])
print('X[2, 2]: (推薦) ', X[2, 2])
print('X[:2, :3]: (前2行前3列)', X[:2, :3])
print('X[:2][:3]: (預料不符)', X[:2][:3])
print('X[:2, ::2]: ', X[:2, ::2])
print('X[: , 0]: (取一列) ', X[:, 0])
subX = X[:2, :3] # 淺拷貝
print("subX:", subX)
print("X: ", X)
X[0, 0] = 999
print("subX:", subX)
print("X: ", X)
# 深拷貝
subX = X[:2, :3].copy()
X[0, 0] = 888
print("subX:", subX)
print("X: ", X)
# Reshape
print('x.shape: ', x.shape)
A = x.reshape((2, 5))
print('x.reshape(2, 5): ', A)
# 只想要十行
tenlines = x.reshape(10, -1) # 每行元素自動計算
print("轉換為10行: ", tenlines)
[out]:
x: [0 1 2 3 4 5 6 7 8 9]
X: [[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
x維度: 1
X維度: 2
X.shape: (3, 5)
X.size: 15
X: [[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
X[0][0]: (不推薦) 0
X[2, 2]: (推薦) 12
X[:2, :3]: (前2行前3列) [[0 1 2]
[5 6 7]]
X[:2][:3]: (預料不符) [[0 1 2 3 4]
[5 6 7 8 9]]
X[:2, ::2]: [[0 2 4]
[5 7 9]]
X[: , 0]: (取一列) [ 0 5 10]
subX: [[0 1 2]
[5 6 7]]
X: [[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
subX: [[999 1 2]
[ 5 6 7]]
X: [[999 1 2 3 4]
[ 5 6 7 8 9]
[ 10 11 12 13 14]]
subX: [[999 1 2]
[ 5 6 7]]
X: [[888 1 2 3 4]
[ 5 6 7 8 9]
[ 10 11 12 13 14]]
x.shape: (10,)
x.reshape(2, 5): [[0 1 2 3 4] [5 6 7 8 9]]
[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]
7.13 合並操作
x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
print('x: ', x)
print('y: ', y)
# 合並操作
print("合並x, y: ", np.concatenate([x, y]))
z = np.array([666, 666, 666])
print('合並x, y, z: ', np.concatenate([x, y, z]))
A = np.array([[1,2,3], [4, 5, 6]])
print('合並兩個A: ', np.concatenate([A, A]))
# 沿着不同維度來合並操作
# axis = 0: 按行來拼接
# axis = 1 按列來拼接
print('axis=0: ', np.concatenate([A, A], axis=0))
print('axos=1: ', np.concatenate([A, A], axis=1))
# 將向量和矩陣合並(按行),不能使用concatenate
print('A和x合並: ', np.concatenate([A, x.reshape(1, -1)]))
print('使用vstack來拼接A和x: (按行)', np.vstack([A, x]))
B = np.full((2, 2), 100)
print('使用hstack來拼接A和B: (按列)', np.hstack([A, B]))
[out1]:
x: [1 2 3]
y: [3 2 1]
合並x, y: [1 2 3 3 2 1]
合並x, y, z: [ 1 2 3 3 2 1 666 666 666]
合並兩個A: [[1 2 3]
[4 5 6]
[1 2 3]
[4 5 6]]
axis=0: [[1 2 3]
[4 5 6]
[1 2 3]
[4 5 6]]
axos=1: [[1 2 3 1 2 3]
[4 5 6 4 5 6]]
A和x合並: [[1 2 3]
[4 5 6]
[1 2 3]]
使用vstack來拼接A和x: (按行) [[1 2 3]
[4 5 6]
[1 2 3]]
使用hstack來拼接A和B: (按列) [[ 1 2 3 100 100]
[ 4 5 6 100 100]]
7.14 分割操作
x = np.arange(10)
print('x: \n', x)
x1, x2, x3 = np.split(x, [3, 7])
print('x1: \n', x1)
print('x2: \n', x2)
print('x3: \n', x3)
print('='*20)
A = np.arange(16).reshape((4, 4))
print('A: \n', A)
A1, A2 = np.split(A, [2]) # np.vsplit(A, [2]): 從第二行開始分割
print('A1: \n', A1)
print('A2; \n', A2)
B1, B2 = np.split(A, [2], axis=1) # np.hsplit(A, [2]): 從第二列開始分割
print('B1: \n', B1)
print('B2: \n', B2)
print('='*20)
data = np.arange(16).reshape((4, 4))
x, y = np.hsplit(data, [-1]) # 分離特征 和 標簽值
print('x: \n', x)
print('y: \n', y)
[out1]:
x:
[0 1 2 3 4 5 6 7 8 9]
x1:
[0 1 2]
x2:
[3 4 5 6]
x3:
[7 8 9]
====================
A:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
A1:
[[0 1 2 3]
[4 5 6 7]]
A2;
[[ 8 9 10 11]
[12 13 14 15]]
B1:
[[ 0 1]
[ 4 5]
[ 8 9]
[12 13]]
B2:
[[ 2 3]
[ 6 7]
[10 11]
[14 15]]
====================
x:
[[ 0 1 2]
[ 4 5 6]
[ 8 9 10]
[12 13 14]]
y:
[[ 3]
[ 7]
[11]
[15]]
7.15 矩陣運算
- 矩陣對應元素間運算:
- A*2, A+2, np.exp(A)等都是對A中所有元素進行操作
- A+B, A*B, A/B: 都是矩陣元素之間對應運算

-
矩陣乘法:
- A.dot(B)
-
矩陣轉置:
- A.T
-
矩陣的逆: \(A*A^{-1}=E\)
- np.linalg.inv(A) (方陣)
- 偽逆矩陣: np.linalg.pinv(x) (非方陣使用)
7.16 聚合操作
import numpy as np
data = np.random.rand(1000000)
%timeit = sum(data)
%timeit = np.sum(data) # 更快
- np.sum(A, axis=0) : 每一列的和
- np.sum(A, axis=1) : 每一行的和
- np.mean(X) : 均值
- np.median(X) : 中位數
- np.percentile(X, q=50) : 求 50% 的數
- np.var(X) : 方差
- np.std(X) : 標准差
7.17 索引
np.min(x)
np.argmin(x) # 返回 min的值的 索引值
np.argmax(x) # 最大值索引
7.18 排序
-
np.sort(A, axis=1) :默認為1,按行排序
- axis=0 : 按列排序
-
np.argsort(x) : 按照索引排序
-
np.partition(x, 3) : 3前面的數字都比他小,后面的都比他大
7.19 FancyIndexing
- X[row, col]
- row, col 為索引組成的向量
import numpy as np
x = np.arange(16)
print(x)
ind = [3, 5, 8]
print(x[ind])
X = x.reshape(4, -1)
print(X)
row = np.array([0, 1, 2, 3])
col = np.array([0, 1, 2, 3])
print("對角線元素: ", X[row, col])
[out1]:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
[3 5 8]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[ 0 5 10 15]
- 重要: 使用bool值
- a = [True, False, False, True]
- X[a] : 這種用法很常用
print(x < 3)
print(x == 3)
print(x*2 == 25 - 4*x)
# 例子: 樣本中有多少小於3歲的人
np.sum(x <= 3)
np.count_nonzero(x <= 3)
# 是否有為0的元素, 有任意一個數為 0 則返回True
np.any(x == 0)
np.any(x < 0) # 有一個 小於0 則返回 True
np.all(x > 0) # 所有元素都 > 0 則返回 True
print(x)
np.sum(~(x==0))
print(X[X[:, 3] % 3 == 0, :])