理論篇
- 什么是機(jī)器學(xué)習(xí)
利用計(jì)算機(jī)從歷史數(shù)據(jù)中查找規(guī)律宋彼,并把它用到對(duì)未來(lái)不確定場(chǎng)景的決策
人:數(shù)據(jù)分析(人為生成規(guī)律)
計(jì)算機(jī):機(jī)器學(xué)習(xí)(自動(dòng)生成規(guī)律)
歷史數(shù)據(jù)越多赫悄,機(jī)器學(xué)習(xí)規(guī)律越準(zhǔn)確
- 從數(shù)據(jù)中尋找規(guī)律
基石:概率論,數(shù)據(jù)統(tǒng)計(jì)
用模型擬合規(guī)律:函數(shù)(多種形態(tài))-> 函數(shù)曲線 -> 擬合
- 機(jī)器學(xué)習(xí)發(fā)展的原動(dòng)力
用數(shù)據(jù)替代專家(避免了主觀性)
經(jīng)濟(jì)驅(qū)動(dòng)态坦,數(shù)據(jù)變現(xiàn)(近年爆火的原因歸功于大數(shù)據(jù))
- 業(yè)務(wù)系統(tǒng)發(fā)展的歷史
基于專家經(jīng)驗(yàn) -> 基于統(tǒng)計(jì)(分維度統(tǒng)計(jì))-> 機(jī)器學(xué)習(xí)(在線學(xué)習(xí))
- 典型應(yīng)用
關(guān)聯(lián)規(guī)則:數(shù)據(jù)算法之購(gòu)物籃分析:“啤酒和尿布”
聚類:用戶細(xì)分精準(zhǔn)營(yíng)銷之移動(dòng):神州行盐数,動(dòng)感地帶,全球通
風(fēng)險(xiǎn)識(shí)別:垃圾郵件(樸素貝葉斯算法)伞梯,信用卡欺詐(決策樹)
點(diǎn)擊預(yù)估:互聯(lián)網(wǎng)廣告(ctr預(yù)估)玫氢,推薦購(gòu)買系統(tǒng)(協(xié)同過(guò)濾)
情感分析,實(shí)體識(shí)別(自然語(yǔ)言處理)谜诫,深度學(xué)習(xí)(圖像識(shí)別)
- 更多應(yīng)用
語(yǔ)音識(shí)別漾峡,人臉識(shí)別,自動(dòng)駕駛喻旷,虛擬助理生逸,實(shí)時(shí)翻譯,手勢(shì)控制
- 數(shù)據(jù)分析和機(jī)器學(xué)習(xí)的區(qū)別
數(shù)據(jù)特點(diǎn)不同:
交易數(shù)據(jù) vs 行為數(shù)據(jù)
少量數(shù)據(jù) vs 海量數(shù)據(jù)
采樣分析 vs 全量分析
參與者不同:
分析師能力決定結(jié)果 vs 數(shù)據(jù)質(zhì)量決定結(jié)果
目標(biāo)用戶不同:
公司高層 vs 個(gè)體
解決問(wèn)題不同:
技術(shù)手段不同:
- 常見算法和分類
1)分類一
有監(jiān)督學(xué)習(xí):有Y值
無(wú)監(jiān)督學(xué)習(xí):聚類且预,無(wú)Y值
半監(jiān)督學(xué)習(xí):強(qiáng)化學(xué)習(xí)
2)分類二
聚類
分類算法與回歸
標(biāo)注:給元素打標(biāo)簽
3)分類三(重要)
生成模型:給函數(shù)槽袄,數(shù)據(jù) -> 結(jié)果帶有概率性(A:30%,B:70%)
判別模型:給函數(shù)锋谐,數(shù)據(jù) -> 結(jié)果帶有肯定性(A:是遍尺,B:不是)
回答問(wèn)題方式不同,思想也不同
- 機(jī)器學(xué)習(xí)解決問(wèn)題
- 圖片識(shí)別demo演示
按照色彩聚類
實(shí)戰(zhàn)篇
- 模擬神經(jīng)元的數(shù)學(xué)表示
- 感知器分類算法
a)權(quán)重更新算法示例
b)適用范圍(第一種)
c)算法步驟總結(jié)
- 實(shí)現(xiàn)感知器對(duì)象
安裝環(huán)境Anaconda Navigator:https://docs.anaconda.com/anaconda/install/
import numpy as np
class Perceptron(object):
# 注釋1
def __init__(self, eta = 0.01, n_iter = 10):
self.eta = eta
self.n_iter = n_iter
def fit(self, X, y):
# 注釋2
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for _ in range(self.n_iter):
errors = 0
# 注釋3
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
# 注釋4
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
def net_input(self, X):
# 注釋5
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1)
注釋1:
eta:學(xué)習(xí)率
n_iter:權(quán)重向量的訓(xùn)練次數(shù)
w_:神經(jīng)分叉權(quán)重向量
errors_:用于記錄神經(jīng)元判斷出錯(cuò)次數(shù)
注釋2:
輸入訓(xùn)練數(shù)據(jù)涮拗,培訓(xùn)神經(jīng)元乾戏,X是輸入樣本向量,y是對(duì)應(yīng)的樣本分類
X:shape[n_samples, n_features]
比如:X:[[1, 2, 3], [4, 5, 6]]
那么:n_samples: 2多搀,n_features: 3歧蕉,y:[1, -1]
初始化權(quán)重向量為0,加1是因?yàn)樘岬降膚0,即步調(diào)函數(shù)的閾值
注釋3:
比如:X:[[1, 2, 3], [4, 5, 6]
所以y:[1, -1]康铭,zip(X, y):[[1, 2, 3, 1]. [4, 5, 6, -1]]
update = n * (y - y')
注釋4:
xi是一個(gè)向量
update * xi等價(jià)于:[ w1 = x1*update, w2 = x2*update, ...]
注釋5:
z = w0*1 + w1*x1 + w2*x2 + ...
np.dot()是做點(diǎn)積
- 數(shù)據(jù)解析和可視化
數(shù)據(jù)文件(iris.data.csv):https://graph-bed-1256708472.cos.ap-chengdu.myqcloud.com/pythondata%2Firis.data.csv
import pandas as pd
file = "C:/Users/YYDL/Desktop/data.csv"
# header=None 數(shù)據(jù)第一行是有用數(shù)據(jù),不是表頭
df = pd.read_csv(file, header = None)
# 顯示文件前十行
df.head(10)
import matplotlib.pyplot as plt
import numpy as np
# 1)
y = df.iloc[0:100, 4].values
print(y)
y = np.where(y == 'Iris-setosa', -1, 1)
X = df.iloc[0:100, [0, 2]].values
print(X)
# 2)
plt.scatter(X[:50, 0], X[:50, 1], color='red', marker='o', label='setosa')
plt.scatter(X[50:100, 0], X[50:100, 1], color='blue', marker='x', label='versicolor')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.xlabel('花莖長(zhǎng)度')
plt.ylabel('花瓣長(zhǎng)度')
plt.legend(loc='upper left')
plt.show()
# 3)
ppn = Perceptron(eta=0.1, n_iter=10)
ppn.fit(X, y)
plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o')
plt.xlabel("Epochs")
plt.ylabel("error count")
plt.show()
1)數(shù)據(jù)可視化
得到數(shù)據(jù)前一百行的第五列
將字符串轉(zhuǎn)化為數(shù)字-1和1
抽取前100條數(shù)據(jù)的第0列和第2列
2)scatter散點(diǎn)繪圖
將前50條數(shù)據(jù)的第0列作為x坐標(biāo)赌髓,第1列作為y坐標(biāo)从藤,點(diǎn)為紅色圓圈
將后50條數(shù)據(jù)的第0列作為x坐標(biāo)催跪,第1列作為y坐標(biāo),點(diǎn)為藍(lán)色叉叉
3)培訓(xùn)神經(jīng)網(wǎng)絡(luò)
輸出模型錯(cuò)誤分類次數(shù)
由圖可知夷野,數(shù)據(jù)滿足感知器分類算法
- 神經(jīng)網(wǎng)絡(luò)對(duì)數(shù)據(jù)實(shí)現(xiàn)分類
from matplotlib.colors import ListedColormap
def plot_decision_region(X, y, classifier, resolution=0.02):
marker = ('s', 'x', 'o', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
# len(np.unique(y))=2
cmap = ListedColormap(colors[:len(np.unique(y))])
# 花莖的長(zhǎng)度
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max()
# 花瓣的長(zhǎng)度
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max()
print(x1_min, x1_max)
print(x2_min, x2_max)
# (備注)
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
# 輸出語(yǔ)句
print(np.arange(x1_min, x1_max, resolution).shape)
print(np.arange(x1_min, x1_max, resolution))
print(xx1.shape)
print(xx1)
print(np.arange(x2_min, x2_max, resolution).shape)
print(np.arange(x2_min, x2_max, resolution))
print(xx2.shape)
print(xx2)
# 執(zhí)行語(yǔ)句
plot_decision_regions(X, y, ppn, resolution=0.02)
備注:
將np.arange()中的向量擴(kuò)展成一個(gè)矩陣
a = np.arange(x1_min, x1_max, resolution) 向量元素為185個(gè)
xx1[255, 185],將a中的元素作為一行懊蒸,重復(fù)255行
b = np.arange(x2_min, x2_max, resolution) 向量元素為255個(gè)
xx2[255, 185],將b中的元素作為一列,重復(fù)185列
from matplotlib.colors import ListedColormap
def plot_decision_region(X, y, classifier, resolution=0.02):
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max()
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max()
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
z = classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T)
z = z.reshape(xx1.shape)
plt.contourf(xx1, xx2, z, alpha=0.4, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.xlim(xx2.min(), xx2.max())
plt.scatter(X[:50,0],X[:50,1],color='red',marker='o',label='setosa')
plt.scatter(X[50:100,0],X[50:100,1],color='blue',marker='x',label='versicolor')
# 執(zhí)行語(yǔ)句
plot_decision_region(X,y,ppn,resolution=0.02)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.xlabel('花莖長(zhǎng)度')
plt.ylabel('花瓣長(zhǎng)度')
plt.legend(loc='upper left')
plt.show()
- 適應(yīng)性線性神經(jīng)元
1)距離的定義
2)漸進(jìn)下降法
- 適應(yīng)性神經(jīng)元代碼實(shí)現(xiàn)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
class Perceptron(object):
def __init__(self, eta = 0.01, n_iter = 10):
self.eta = eta
self.n_iter = n_iter
def fit(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for _ in range(self.n_iter):
errors = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1)
file = "C:/Users/YYDL/Desktop/data.csv"
df = pd.read_csv(file, header = None)
y = df.iloc[0:100, 4].values
y = np.where(y == 'Iris-setosa', -1, 1)
X = df.iloc[0:100, [0, 2]].values
ppn = Perceptron(eta=0.1, n_iter=10)
ppn.fit(X, y)
def plot_decision_region(X, y, classifier, resolution=0.02):
marker = ('s', 'x', 'o', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max()
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max()
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
class AdalineGD(object):
def __init__(self, eta=0.01, n_iter=50):
self.eta = eta
self.n_iter = n_iter
def fit(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
self.cost_ = []
for i in range(self.n_iter):
output = self.net_input(X)
errors = (y - output)
# 和方差求偏導(dǎo)數(shù)
self.w_[1:] += self.eta * X.T.dot(errors)
# 神經(jīng)元參數(shù)更新
self.w_[0] += self.eta * errors.sum()
cost = (errors ** 2).sum() / 2.0
self.cost_.append(cost)
return self
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def activation(self, X):
return self.net_input(X)
def predict(self, X):
return np.where(self.activation(X) >= 0, 1, -1)
# 神經(jīng)網(wǎng)絡(luò)對(duì)象ada悯搔,學(xué)習(xí)率0.0001骑丸,訓(xùn)練次數(shù)50
ada = AdalineGD(eta = 0.0001, n_iter = 50)
# 迭代訓(xùn)練神經(jīng)網(wǎng)絡(luò)
ada.fit(X, y)
# 構(gòu)造預(yù)測(cè)數(shù)據(jù),輸入模型進(jìn)行分類
plot_decision_region(X, y, classifier = ada)
# 繪圖展示
plt.plot(range(1, len(ada.cost_)+1), ada.cost_, marker='o')
plt.xlabel('Epochs')
plt.ylabel('sum-squard-error')
plt.show()