監(jiān)督學(xué)習(xí)
目標值:類別--分類問題
目標值:連續(xù)型的數(shù)據(jù)--回歸問題
分類模型
k近鄰算法壳坪,貝葉斯分類澡罚,決策樹與隨機森林,邏輯回歸,SVM,
回歸模型
線性回歸夸政,嶺回歸
無監(jiān)督學(xué)習(xí)
目標值:無
聚類模型
k-means
機器學(xué)習(xí)開發(fā)流程
- 獲取數(shù)據(jù)
- 數(shù)據(jù)清洗
- 特征工程(特征值與目標值)
- 機器學(xué)習(xí)算法訓(xùn)練
- 模型評估(不好則重新開始)
分類算法
K近鄰-KNN
用官方的話來說闰围,所謂K近鄰算法赃绊,即是給定一個訓(xùn)練數(shù)據(jù)集碧查,對新的輸入實例忠售,在訓(xùn)練數(shù)據(jù)集中找到與該實例最鄰近的K個實例(也就是上面所說的K個鄰居)迄沫, 這K個實例的多數(shù)屬于某個類羊瘩,就把該輸入實例分類到這個類中。多分類逝她。
如圖1所示,有兩類不同的樣本數(shù)據(jù)睬捶,分別用藍色的小正方形和紅色的小三角形表示黔宛,而圖正中間的那個綠色的圓所標示的數(shù)據(jù)則是待分類的數(shù)據(jù)。也就是說擒贸,現(xiàn)在臀晃, 我們不知道中間那個綠色的數(shù)據(jù)是從屬于哪一類(藍色小正方形or紅色小三角形),下面酗宋,我們就要解決這個問題:給這個綠色的圓分類积仗。
我們常說,物以類聚蜕猫,人以群分寂曹,判別一個人是一個什么樣品質(zhì)特征的人,常郴赜遥可以從他/她身邊的朋友入手隆圆,所謂觀其友,而識其人翔烁。我們不是要判別圖1中那個綠色的圓是屬于哪一類數(shù)據(jù)么渺氧,好說,從它的鄰居下手蹬屹。但一次性看多少個鄰居呢白华?從圖1中,你還能看到:
- 如果K=3管搪,綠色圓點的最近的3個鄰居是2個紅色小三角形和1個藍色小正方形,少數(shù)從屬于多數(shù)澡为,基于統(tǒng)計的方法,判定綠色的這個待分類點屬于紅色的三角形一類塘慕。
- 如果K=5图呢,綠色圓點的最近的5個鄰居是2個紅色三角形和3個藍色的正方形,還是少數(shù)從屬于多數(shù)指蚜,基于統(tǒng)計的方法,判定綠色的這個待分類點屬于藍色的正方形一類免猾。
于此我們看到,當(dāng)無法判定當(dāng)前待分類點是從屬于已知分類中的哪一類時锨苏,我們可以依據(jù)統(tǒng)計學(xué)的理論看它所處的位置特征松逊,衡量它周圍鄰居的權(quán)重犀暑,而把它歸為(或分配)到權(quán)重更大的那一類徊都。這就是K近鄰算法的核心思想。
sklearn 實現(xiàn)
from sklearn import datasets
#導(dǎo)入內(nèi)置數(shù)據(jù)集模塊
from sklearn.neighbors import KNeighborsClassifier
#導(dǎo)入sklearn.neighbors模塊中KNN類
import numpy as np
np.random.seed(0)
#設(shè)置隨機種子李根,不設(shè)置的話默認是按系統(tǒng)時間作為參數(shù),因此每次調(diào)用隨機模塊時產(chǎn)生的隨機數(shù)都不一樣設(shè)置后每次產(chǎn)生的一樣
iris=datasets.load_iris()
#導(dǎo)入鳶尾花的數(shù)據(jù)集囱持,iris是一個類似于結(jié)構(gòu)體的東西,內(nèi)部有樣本數(shù)據(jù)掩幢,如果是監(jiān)督學(xué)習(xí)還有標簽數(shù)據(jù)
iris_x=iris.data
#樣本數(shù)據(jù)150*4二維數(shù)據(jù),代表150個樣本枯怖,每個樣本4個屬性分別為花瓣和花萼的長肿轨、寬
iris_y=iris.target
indices = np.random.permutation(len(iris_x))
#permutation接收一個數(shù)作為參數(shù)(150),產(chǎn)生一個0-149一維數(shù)組椒袍,只不過是隨機打亂的,當(dāng)然她也可以接收一個一維數(shù)組作為參數(shù)优俘,結(jié)果是直接對這個數(shù)組打亂
indices[:-10]
array([114, 62, 33, 107, 7, 100, 40, 86, 76, 71, 134, 51, 73,
54, 63, 37, 78, 90, 45, 16, 121, 66, 24, 8, 126, 22,
44, 97, 93, 26, 137, 84, 27, 127, 132, 59, 18, 83, 61,
92, 112, 2, 141, 43, 10, 60, 116, 144, 119, 108, 69, 135,
56, 80, 123, 133, 106, 146, 50, 147, 85, 30, 101, 94, 64,
89, 91, 125, 48, 13, 111, 95, 20, 15, 52, 3, 149, 98,
6, 68, 109, 96, 12, 102, 120, 104, 128, 46, 11, 110, 124,
41, 148, 1, 113, 139, 42, 4, 129, 17, 38, 5, 53, 143,
105, 0, 34, 28, 55, 75, 35, 23, 74, 31, 118, 57, 131,
65, 32, 138, 14, 122, 19, 29, 130, 49, 136, 99, 82, 79,
115, 145, 72, 77, 25, 81, 140, 142, 39, 58])
iris_x_train = iris_x[indices[:-10]]
#隨機選取140個樣本作為訓(xùn)練數(shù)據(jù)集
iris_y_train = iris_y[indices[:-10]]
#并且選取這140個樣本的標簽作為訓(xùn)練數(shù)據(jù)集的標簽
iris_x_test = iris_x[indices[-10:]]
#剩下的10個樣本作為測試數(shù)據(jù)集
iris_y_test = iris_y[indices[-10:]]
#并且把剩下10個樣本對應(yīng)標簽作為測試數(shù)據(jù)及的標簽
knn = KNeighborsClassifier()
#定義一個knn分類器對象,n_neighbors=5 ,knn算法中指定以最近的幾個最近鄰樣本具有投票權(quán)不恭,默認參數(shù)為5
knn.fit(iris_x_train, iris_y_train)
#調(diào)用該對象的訓(xùn)練方法折晦,主要接收兩個參數(shù):訓(xùn)練數(shù)據(jù)集及其樣本標簽
knn.fit(iris_x_train, iris_y_train)
#調(diào)用該對象的訓(xùn)練方法,主要接收兩個參數(shù):訓(xùn)練數(shù)據(jù)集及其樣本標簽
iris_y_predict = knn.predict(iris_x_test)
#調(diào)用該對象的測試方法漓滔,主要接收一個參數(shù):測試數(shù)據(jù)集
probility=knn.predict_proba(iris_x_test)
#計算各測試樣本基于概率的預(yù)測
score=knn.score(iris_x_test,iris_y_test,sample_weight=None)
#調(diào)用該對象的打分方法,計算出準確率
iris_y_predict
array([1, 2, 1, 0, 0, 0, 2, 1, 2, 0])
probility
array([[0. , 1. , 0. ],
[0. , 0.4, 0.6],
[0. , 1. , 0. ],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[0. , 0. , 1. ],
[0. , 1. , 0. ],
[0. , 0. , 1. ],
[1. , 0. , 0. ]])
score
0.9
參考
Sklearn中的knn算法基本講解_偏執(zhí)灬的博客-CSDN博客_knn sklearn
樸素貝葉斯
基于統(tǒng)計學(xué)的貝葉斯分類方法以貝葉斯理論為基礎(chǔ)豁鲤,通過求解后驗概率分布,預(yù)測樣本屬于某一類別的概率楣号。貝葉斯分類的主要算法是貝葉斯公式:
換一種表達方式:
我們最終求的p(類別|特征)即可!就相當(dāng)于完成了我們的任務(wù)嬉荆。
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
gnb.fit(iris_x_train, iris_y_train)
iris_y_predict = gnb.predict(iris_x_test)
#調(diào)用該對象的測試方法,主要接收一個參數(shù):測試數(shù)據(jù)集
probility=gnb.predict_proba(iris_x_test)
#計算各測試樣本基于概率的預(yù)測
score=gnb.score(iris_x_test,iris_y_test,sample_weight=None)
#調(diào)用該對象的打分方法蝶锋,計算出準確率
參考
貝葉斯分類(通過通俗的例子輕松理解樸素貝葉斯與半樸素貝葉斯)月亮是藍色的博客-CSDN博客貝葉斯分類
SVM
支持向量機(Support Vector Machine, SVM)是一類按監(jiān)督學(xué)習(xí)(supervised learning)方式對數(shù)據(jù)進行二元分類的廣義線性分類器(generalized linear classifier)别威,其決策邊界是對學(xué)習(xí)樣本求解的最大邊距超平面(maximum-margin hyperplane)
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from time import time
import numpy as np
import datetim
data = load_breast_cancer()
X = data.data # (569, 30)
y = data.target # (569,) 0 1
# 對數(shù)據(jù)進行標準化
X = StandardScaler().fit_transform(X)
cv = StratifiedShuffleSplit(n_splits=5, test_size=0.3, random_state=420) #分層抽樣
for train_index, test_index in cv.split(X, y):
# print("TRAIN:", train_index, "TEST:", test_index)#獲得索引值
X_train, X_test = X[train_index], X[test_index]#訓(xùn)練集對應(yīng)的值
y_train, y_test = y[train_index], y[test_index]#類別集對應(yīng)的值
clf_svc = SVC(kernel="linear",probability=True)
clf_svc.fit(X_train,y_train)
# 導(dǎo)入模型并訓(xùn)練
iris_y_predict = clf_svc.predict(X_test)
#調(diào)用該對象的測試方法,主要接收一個參數(shù):測試數(shù)據(jù)集
probility=clf_svc.predict_proba(X_test)
#計算各測試樣本基于概率的預(yù)測
score=clf_svc.score(X_test,y_test,sample_weight=None)
#調(diào)用該對象的打分方法豺妓,計算出準確率
混淆矩陣(Confusion Matrix)
混淆矩陣就是把所有類別的預(yù)測結(jié)果與真實結(jié)果按類別放置到了同一個表里描验,在這個表格中我們可以清楚看到每個類別正確識別的數(shù)量和錯誤識別的數(shù)量絮缅。
ROC曲線(receiver operating characteristic curve耕魄,簡稱ROC曲線),以TPR為y軸,以FPR為x軸蔼两,我們就直接得到了RoC曲線额划。從FPR和TPR的定義可以理解,TPR越高抑胎,F(xiàn)PR越小,我們的模型和算法就越高效恃锉。也就是畫出來的RoC曲線越靠近左上越好。如下圖左圖所示土砂。從幾何的角度講,RoC曲線下方的面積越大越大锌俱,則模型越優(yōu)贸宏。所以有時候我們用RoC曲線下的面積,即AUC(Area Under Curve)值來作為算法和模型好壞的標準鲫咽。
from sklearn.metrics import roc_curve, auc
y_score = clf_svc.decision_function(X_test) #通過decision_function()計算得到的y_score的值,用在roc_curve()函數(shù)中
fpr, tpr, threshold = roc_curve(y_test, y_score) #
roc_auc = auc(fpr,tpr)
plt.figure()
lw = 2
plt.figure(figsize=(10,10))
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) ###假正率為橫坐標孔庭,真正率為縱坐標做曲線
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
參考
- 機器學(xué)習(xí):混淆矩陣、準確率芽淡、錯誤率、靈敏度己单、特異度纹份、精準率件已、召回率、F-Measure鉴未、ROC曲線 & PR曲線SunshineSki的博客-CSDN博客混淆矩陣 靈敏度
- 機器學(xué)習(xí)之混淆矩陣 (baidu.com)
- sklearn之SVM,ROC曲線與AUC面積_thereisnospoon.的博客-CSDN博客
決策樹
決策樹(Decision Tree)是在已知各種情況發(fā)生概率的基礎(chǔ)上连茧,通過構(gòu)成決策樹來求取凈現(xiàn)值的期望值大于等于零的概率客扎,評價項目風(fēng)險,判斷其可行性的決策分析方法疆偿,是直觀運用概率分析的一種圖解法杆故。由于這種決策分支畫成圖形很像一棵樹的枝干处铛,故稱決策樹。
決策樹是一種樹形結(jié)構(gòu)家肯,其中每個內(nèi)部節(jié)點表示一個屬性上的判斷,每個分支代表一個判斷結(jié)果的輸出反镇,最后每個葉節(jié)點代表一種分類結(jié)果。
class sklearn.tree.DecisionTreeClassifier(*, criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, class_weight=None, ccp_alpha=0.0)
# 導(dǎo)入需要的算法庫和模塊
from sklearn import tree
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
import graphviz
# 探索數(shù)據(jù),也就是查看數(shù)據(jù)長什么樣子
wine = load_wine()
print(wine.data.shape) #(178, 13)
print(wine.target)
# 查看表長什么樣子
import pandas as pd
table=pd.concat([pd.DataFrame(wine.data),pd.DataFrame(wine.target)],axis=1)
print(table)
#查看表頭的名字
print(wine.feature_names)
#查看表的分類
print(wine.target_names)
['alcohol', 'malic_acid', 'ash', 'alcalinity_of_ash', 'magnesium', 'total_phenols', 'flavanoids', 'nonflavanoid_phenols', 'proanthocyanins', 'color_intensity', 'hue', 'od280/od315_of_diluted_wines', 'proline']
['class_0' 'class_1' 'class_2']
Xtrain, Xtest, Ytrain, Ytest = train_test_split(wine.data,wine.target,test_size=0.3)
print(Xtrain.shape) #(124, 13)
print(Xtest.shape) #(54, 13)
clf = tree.DecisionTreeClassifier(criterion="entropy")
clf = clf.fit(Xtrain, Ytrain)
score = clf.score(Xtest, Ytest) #返回預(yù)測的準確度
print(score)
feature_name = ['酒精','蘋果酸','灰','灰的堿性','鎂','總酚','類黃酮','非黃烷類酚類','花青素','顏色強度','色調(diào)','od280/od315稀釋葡萄酒','脯氨酸']
import graphviz
dot_data = tree.export_graphviz(clf
,out_file = None
,feature_names = feature_name
,class_names=["琴酒","雪莉","貝爾摩德"]
,filled=True #顏色填充
,rounded=True #框框的圓角
)
graph = graphviz.Source(dot_data.replace("helvetica", "MicrosoftYaHei"))
graph.view()
[*zip(feature_name,clf.feature_importances_)]
[('酒精', 0.03473796489031354),
('蘋果酸', 0.0),
('灰', 0.0),
('灰的堿性', 0.0),
('鎂', 0.0),
('總酚', 0.0),
('類黃酮', 0.06831747799131759),
('非黃烷類酚類', 0.0),
('花青素', 0.0),
('顏色強度', 0.15799189175636455),
('色調(diào)', 0.0),
('od280/od315稀釋葡萄酒', 0.4238563513218273),
('脯氨酸', 0.315096314040177)]
參考
sklearn專題一:決策樹_Colorfully_lu的博客-CSDN博客_sklearn 決策樹
隨機森林
隨機森林指的是利用多棵樹對樣本進行訓(xùn)練并預(yù)測的一種分類器。
隨機選取不同的數(shù)據(jù)集是為了保證每個決策樹看待問題的角度不同彻磁,以便輸出相似但不相同的模型結(jié)果累提,再講所有決策樹結(jié)果整合在一起,作為輸出結(jié)果置吓,而這一訓(xùn)練方式友题,意味著很難過擬合度宦,并且對噪音不敏感。
隨機森林的優(yōu)缺點
優(yōu)點
- 模型隨機性強划鸽,不易過擬合;
- 模型抗噪聲性強,對異常點outliter不敏感啰脚;
- 處理高維數(shù)據(jù)集相比較快,比決策樹更快荸实;
- 樹狀結(jié)構(gòu)准给,模型可解釋性高祖灰,可以體現(xiàn)出每個特征的重要性;
缺點
- 模型往往過于general叁扫,不具備正確處理過于復(fù)雜困難樣本的能力畴蒲,這是因為模型對異常點不敏感,隨機森林不專注于解決困難樣本涧窒;
- 模型起點高,但天花板低戴已;
class sklearn.ensemble.RandomForestClassifier(n_estimators=100, *, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='sqrt', max_leaf_nodes=None, min_impurity_decrease=0.0, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None)
# 導(dǎo)入基本庫
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier as dtc
from sklearn.ensemble import RandomForestClassifier as rfc
from sklearn.model_selection import cross_val_score
#決策樹本身就是非常容易過擬合的算法,而集成模型的參數(shù)量/復(fù)雜度很難支持大規(guī)模網(wǎng)格搜索
#因此對于隨機森林來說握联,一定要關(guān)注算法的過擬合情況
wine=load_wine()
x=pd.DataFrame(wine.data,columns=wine.feature_names)
y=wine.target
xtrain,xtest,ytrain,ytest = train_test_split(x,y,test_size=0.3,random_state=1)
# 建模對比
clf_tree=dtc().fit(xtrain,ytrain)
clf_cf=rfc().fit(xtrain,ytrain)
score_tree=clf_tree.score(xtest,ytest)
score_cf=clf_cf.score(xtest,ytest)
print(score_tree,score_cf)
plt.rcParams['font.sans-serif'] = ['SimHei']
rfc_s = cross_val_score(rfc(),x,y,cv=10)
dtc_s = cross_val_score(dtc(),x,y,cv=10)
plt.plot(range(1,11),rfc_s,label = "RandomForest")
plt.plot(range(1,11),dtc_s,label = "Decision Tree")
plt.legend()
plt.title("隨機森林和決策樹在一組交叉驗證下的效果對比")
plt.show()
參數(shù)調(diào)整和決策樹類似
參考
機器學(xué)習(xí) | 隨機森林 - 知乎 (zhihu.com)
神經(jīng)網(wǎng)絡(luò)-分類
人工神經(jīng)網(wǎng)絡(luò)(Artificial Neural Networks剿骨,簡寫為ANNs)也簡稱為神經(jīng)網(wǎng)絡(luò)(NNs)或稱作連接模型(Connection Model)浓利,它是一種模仿動物神經(jīng)網(wǎng)絡(luò)行為特征,進行分布式并行信息處理的算法數(shù)學(xué)模型玉工。這種網(wǎng)絡(luò)依靠系統(tǒng)的復(fù)雜程度,通過調(diào)整內(nèi)部大量節(jié)點之間相互連接的關(guān)系,從而達到處理信息的目的汇在。*class *sklearn.neural_network.MLPClassifier(*hidden_layer_sizes=(100,)*, *activation='relu'*, ***, *solver='adam'*, *alpha=0.0001*, *batch_size='auto'*, *learning_rate='constant'*, *learning_rate_init=0.001*, *power_t=0.5*, *max_iter=200*, *shuffle=True*, *random_state=None*, *tol=0.0001*, *verbose=False*, *warm_start=False*, *momentum=0.9*, *nesterovs_momentum=True*, *early_stopping=False*, *validation_fraction=0.1*, *beta_1=0.9*, *beta_2=0.999*, *epsilon=1e-08*, *n_iter_no_change=10*, *max_fun=15000*)[[source]](https://github.com/scikit-learn/scikit-learn/blob/36958fb24/sklearn/neural_network/_multilayer_perceptron.py#L793)
from sklearn.datasets import load_digits
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn import metrics
data = load_digits()
x = data.data
y = data.target
print(x.shape,y.shape)
stander = MinMaxScaler()
x = stander.fit_transform(x)
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3)
clf = MLPClassifier(hidden_layer_sizes=(100,100))
clf.fit(x_train,y_train)
y_pred = clf.predict((x_test))
print("訓(xùn)練集評分:", clf.score(x_train,y_train))
print("測試集評分:", clf.score(x_test,y_test))
print("混淆矩陣:")
print(metrics.confusion_matrix(y_test,y_pred))
(1797, 64) (1797,)
訓(xùn)練集評分: 1.0
測試集評分: 0.975925925925926
混淆矩陣:
[[51 0 0 0 0 0 1 0 0 0]
[ 0 49 0 0 0 0 0 0 1 0]
[ 0 0 63 0 0 0 0 0 0 0]
[ 0 0 0 55 0 2 0 2 0 0]
[ 0 0 0 0 56 0 0 0 0 0]
[ 0 0 0 0 0 46 0 0 0 0]
[ 0 0 0 0 0 0 53 0 0 0]
[ 0 0 0 0 0 0 0 56 0 2]
[ 0 0 1 0 0 1 0 0 54 2]
[ 0 0 0 0 0 1 0 0 0 44]]
參考
一文了解神經(jīng)網(wǎng)絡(luò)工作原理-51CTO.COM
神經(jīng)網(wǎng)絡(luò)③——sklearn參數(shù)介紹及應(yīng)用數(shù)據(jù)小斑馬的博客-CSDN博客神經(jīng)網(wǎng)絡(luò)sklearn
sklearn 神經(jīng)網(wǎng)絡(luò)MLPclassifier參數(shù)詳解_九點澡堂子的博客-CSDN博客_mlpclassifier
分層采樣
你的數(shù)據(jù)集很大時(尤其是和屬性數(shù)相比)阿蝶,純隨機的取樣方法通崇韫可行;但如果數(shù)據(jù)集不大,就會有采樣偏差的風(fēng)險袋马。當(dāng)一個調(diào)查公司想要對 1000 個人進行調(diào)查,它們不是在電話亭里隨機選 1000 個人出來墓懂。調(diào)查公司要保證這 1000 個人對人群整體有代表性匕积。例如闪唆,美國人口的 51.3% 是女性悄蕾,48.7% 是男性。所以在美國含鳞, 嚴謹?shù)恼{(diào)查需要保證樣本也是這個比例:513 名女性,487 名男性熔吗。這稱作分層采樣 (stratified sampling):將人群分成均勻的子分組,稱為分層垂攘,從每個分層去取合適數(shù)量的實例逸贾,以保證測試集對總?cè)藬?shù)有代表性灼伤。如果調(diào)查公司采用純隨機采樣,會有 12% 的概率導(dǎo)致采樣偏差:女性人數(shù)少于 49%鸟雏,或多于 54%孝鹊。不管發(fā)生那種情況皇钞,調(diào)查結(jié)果都會嚴重偏差。
純隨機的取樣方法松捉,即沒有對原數(shù)據(jù)集進行分層:
from sklearn.model_selection import train_test_split
xtrain,xtest,ytrain,ytest = train_test_split(x,y,test_size=0.3,random_state=1)
分層采樣夹界,對原始數(shù)據(jù)進行分層
# 分層抽樣 訓(xùn)練測試
from sklearn.model_selection import StratifiedShuffleSplit
sss = StratifiedShuffleSplit(n_splits=5, test_size=0.2, random_state=randoms)
for train_index, test_index in sss.split(X, y): # 這里循環(huán)的次數(shù)由n_splits決定,前面指定的5
#print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
交叉驗證
交叉驗證是在機器學(xué)習(xí)建立模型和驗證模型參數(shù)時常用的辦法隘世,一般被用于評估一個機器學(xué)習(xí)模型的表現(xiàn)可柿。更多的情況下丙者,我們也用交叉驗證來進行模型選擇(model selection)痢虹。
交叉驗證,顧名思義,就是重復(fù)的使用數(shù)據(jù),把得到的樣本數(shù)據(jù)進行切分硼被,組合為不同的訓(xùn)練集和測試集,用訓(xùn)練集來訓(xùn)練模型负懦,用測試集來評估模型預(yù)測的好壞。在此基礎(chǔ)上可以得到多組不同的訓(xùn)練集和測試集,某次訓(xùn)練集中的某樣本在下次可能成為測試集中的樣本峰档,即所謂“交叉”槽棍。
那么什么時候才需要交叉驗證呢?交叉驗證用在數(shù)據(jù)不是很充足的時候拼岳。如果數(shù)據(jù)樣本量小于一萬條,我們就會采用交叉驗證來訓(xùn)練優(yōu)化選擇模型虑瀑。如果樣本大于一萬條的話,我們一般隨機的把數(shù)據(jù)分成三份君丁,一份為訓(xùn)練集(Training Set),一份為驗證集(Validation Set),最后一份為測試集(Test Set)秉剑。用訓(xùn)練集來訓(xùn)練模型渊涝,用驗證集來評估模型預(yù)測的好壞和選擇模型及其對應(yīng)的參數(shù)捷绒。把最終得到的模型再用于測試集,最終決定使用哪個模型以及對應(yīng)參數(shù)金拒。
k折交叉驗證 k-fold cross validation
首先隨機地將數(shù)據(jù)集切分為 k 個互不相交的大小相同的子集;
然后將 k-1 個子集當(dāng)成訓(xùn)練集訓(xùn)練模型圣勒,剩下的 (held out) 一個子集當(dāng)測試集測試模型啄骇;將上一步對可能的 k 種選擇重復(fù)進行 (每次挑一個不同的子集做測試集);這樣就訓(xùn)練了 k 個模型,每個模型都在相應(yīng)的測試集上計算測試誤差蘸吓,得到了 k 個測試誤差居凶,對這 k 次的測試誤差取平均便得到一個交叉驗證誤差。這便是交叉驗證的過程。
from sklearn.model_selection import KFold
from sklearn.datasets import load_iris
from sklearn.linear_model import LinearRegression
import numpy as np
import pandas as pd
KF = KFold(n_splits=5)
X, Y = load_iris().data, load_iris().target
alg = LinearRegression()
# 這里想強行使用DataFrame的數(shù)據(jù)格式闯割,因為以后大家讀取數(shù)據(jù)使用都是csv格式
# 所以必不可免要用 iloc
X, Y = pd.DataFrame(X), pd.DataFrame(Y)
# split():Generate indices to split data into training and test set.
for train_index, test_index in KF.split(X):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = Y.iloc[train_index], Y.iloc[test_index]
alg.fit(X_train, y_train)
sklearn.model_selection.cross_val_score(estimator, X, y=None, *, groups=None, scoring=None, cv=None, n_jobs=None, verbose=0, fit_params=None, pre_dispatch='2*n_jobs', error_score=nan)
參數(shù):
estimator:模型算法對象列林。比如lin_reg.
X : 訓(xùn)練樣本。
y:樣本標簽。
cv : int, cross-validation generator or an iterable, default=None. 確定交叉驗證的數(shù)據(jù)集劃分策略朦佩。
cross-validation generator的話就是1.中講的那些放方法,所以可以傳kf界弧,loo素标,lpo,
int的話掷贾,就是指幾折蚕礼,然后用普通的kfold.
# 使用交叉驗證評估模型
lin_reg = LinearRegression()
# 先劃分訓(xùn)練集和測試集,75%訓(xùn)練
X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, shuffle=True, random_state=0)
# 10折交叉驗證評分
score = cross_val_score(estimator=lin_reg, X=X_train, y=y_train, cv=10)
print('交叉驗證評分:\n', score, sep='')
# cross_val_score這一個函數(shù)干了很多事情吨拗,劃分數(shù)據(jù)集华望、對每個劃分進行了訓(xùn)練紧显、對每個劃分進行了測試評分。
交叉驗證可以有效評估模型的質(zhì)量
交叉驗證可以有效選擇在數(shù)據(jù)集上表現(xiàn)最好的模型
交叉驗證可以有效避免過擬合和欠擬合
?? 欠擬合(Underfitting)
? 是指模型不能獲取數(shù)據(jù)集的主要信息承冰,在訓(xùn)練集及測試集上的表示都十分糟糕。
?? 過擬合(Overfitting)
??是指模型不僅獲取了數(shù)據(jù)集的信息還提取了噪聲數(shù)據(jù)的信息是的模型在訓(xùn)練集有非常好的表現(xiàn)但在測試集上的表現(xiàn)及其糟糕食零。
參考
機器學(xué)習(xí) 交叉驗證 sklearn_Michael_Flemming的博客-CSDN博客_sklearn的交叉驗證
交叉驗證(Cross-Validation)南有芙蕖的博客-CSDN博客交叉驗證
網(wǎng)格搜索 GridSearch
網(wǎng)格搜索算法是一種通過遍歷給定的參數(shù)組合來優(yōu)化模型表現(xiàn)的方法困乒。它是一種窮舉方法。給定一系列超參贰谣,然后再所有超參組合中窮舉遍歷娜搂,從所有組合中選出最優(yōu)的一組超參數(shù),其實就是暴力方法在全部解中找最優(yōu)解吱抚。
使用內(nèi)置乳腺癌數(shù)據(jù)來訓(xùn)練支持向量分類(SVC)百宇。可以通過load_breast_cancer函數(shù)獲取數(shù)據(jù):
import pandas as pd
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
df_X = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])
df_X.head()
df_y = pd.DataFrame(cancer['target'], columns=['Cancer'])
df_y.head()
# train test split
from sklearn.model_selection import train_test_split
import numpy as np
X_train, X_test, y_train, y_test = train_test_split(df_X, np.ravel(df_y), test_size=0.3)
我們將訓(xùn)練支持向量分類器(SVC) 模型秘豹。正則化參數(shù)C和核系數(shù)gamma是 SVC 中最重要的兩個超參數(shù):
正則化參數(shù)C決定了正則化的強度携御。
核系數(shù)gamma控制核的寬度。SVC默認使用徑向基函數(shù) (RBF)核(也稱為高斯核)。
最優(yōu)值C和gamma是比較難找得到的啄刹。最簡單的解決方案是嘗試一堆組合涮坐,看看哪種組合效果最好。這種創(chuàng)建參數(shù)“網(wǎng)格”并嘗試所有可能組合的方法稱為網(wǎng)格搜索誓军。
這種方法非常常見膊升,所以Scikit-learn在GridSearchCV中內(nèi)置了這種功能。CV 代表交叉驗證谭企,這是另一種評估和改進機器學(xué)習(xí)模型的技術(shù)廓译。
GridSearchCV需要一個描述準備嘗試的參數(shù)和要訓(xùn)練的模型的字典。網(wǎng)格搜索的參數(shù)網(wǎng)格定義為字典债查,其中鍵是參數(shù)非区,值是要測試的一系列設(shè)置值。下面動手試試,首先定義候選參數(shù)C和gamma,如下所示:
param_grid = {
'C': [0.1, 1, 10, 100, 1000],
'gamma': [1, 0.1, 0.01, 0.001, 0.0001]
}
接下來創(chuàng)建一個GridSearchCV對象赖晶,并使用訓(xùn)練數(shù)據(jù)進行訓(xùn)練模型。
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
grid = GridSearchCV(
SVC(),
param_grid,
refit=True,
verbose=3
)
一旦訓(xùn)練完成后管怠,我們可以通過GridSearchCV的best_params_屬性查看搜索到的最佳參數(shù),并使用best_estimator_屬性查看最佳模型:
# 找到最好的參數(shù)
grid.best_params_
# 找到最好的模型
grid.best_estimator_
訓(xùn)練完成后缸榄,現(xiàn)在選擇并采用該網(wǎng)格搜索到的最佳模型渤弛,并使用測試集進行預(yù)測
# 使用最好的估計器進行預(yù)測
grid_predictions = grid.predict(X_test)
參考
網(wǎng)格搜索、隨機搜索和貝葉斯搜索實用教程_風(fēng)度78的博客-CSDN博客
回歸
多元線性回歸 LinearRegression
線性回歸是機器學(xué)習(xí)中最簡單的回歸算法甚带,多元線性回歸指的就是一個樣本有多個特征的線性回歸問題她肯。對于一個n有 i 個特征的樣本 而言,它的回歸結(jié)果可以寫作一個幾乎人人熟悉的方程:
class sklearn.linear_model.LinearRegression(*, fit_intercept=True, normalize='deprecated', copy_X=True, n_jobs=None, positive=False)
沒有對我們的模型有不可替代作用的參數(shù)鹰贵,這說明晴氨,線性回歸的性能,往往取決于數(shù)據(jù)本身碉输,而并非是我們的調(diào)參能力籽前,線性回歸也因此對數(shù)據(jù)有著很高的要求.
from sklearn.linear_model import LinearRegression as LR
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.datasets import fetch_california_housing as fch #加利福尼亞房屋價值數(shù)據(jù)集
import pandas as pd
housevalue = fch() #會需要下載,大家可以提前運行試試看
X = pd.DataFrame(housevalue.data) #放入DataFrame中便于查看
y = housevalue.target
Xtrain, Xtest, Ytrain, Ytest = train_test_split(X,y,test_size=0.3,random_state=420)
# 恢復(fù)索引
for i in [Xtrain, Xtest]:
i.index = range(i.shape[0])
Xtrain.shape
reg = LR().fit(Xtrain, Ytrain)
yhat = reg.predict(Xtest)
yhat
reg.coef_
[*zip(Xtrain.columns,reg.coef_)]
reg.intercept_
評估指標
MSE :
sklearn中使用RSS的變體敷钾,均方誤差MSE(mean squared error)來衡量我們的預(yù)測值和真實值的差異:
from sklearn.metrics import mean_squared_error as MSE
MSE(yhat,Ytest)
對于某些擬合模型枝哄,如果我們使用MSE來對它進行判斷,它的MSE會很小闰非,當(dāng)大部分樣本其實都被完美擬合了膘格,少數(shù)樣本的真實值和預(yù)測值的巨大差異在被均分到每個樣本上之后峭范,MSE就會很小财松。但這樣的擬合結(jié)果必然不是一個好結(jié)果,因為一旦我的新樣本是處于擬合曲線的后半段的,我的預(yù)測結(jié)果必然會有巨大的偏差辆毡,而這不是我們希望看到的菜秦。所以,我們希望找到新的指標舶掖,除了判斷預(yù)測的數(shù)值是否正確之外球昨,還能夠判斷我們的模型是否擬合了足夠多的,數(shù)值之外的信息眨攘。
R^2:
可解釋性方差分數(shù)(explained_variance_score主慰,EVS):
from sklearn.metrics import r2_score
r2_score(Ytest,yhat)
#或者直接指定參數(shù)
r2_score(y_true = Ytest,y_pred = yhat)
嶺回歸
class sklearn.linear_model.Ridge(alpha=1.0, fit_intercept=True,
normalize=False, copy_X=True,max_iter=None, tol=0.001, solver=auto’ ,
random_state=None)
from sklearn.linear_model import Ridge
reg = Ridge(alpha=1).fit(Xtrain, Ytrain)
reg.score(Xtest,Ytest)
#交叉驗證下,與線性回歸相比鲫售,嶺回歸的結(jié)果如何變化共螺?
import numpy as np
alpharange =np.arange(1,1001,100)
ridge ,lr=[],[]
for alpha in alpharange:
reg=Ridge(alpha=alpha)
linear=LR()
regs=cross_val_score(reg,X,y,cv=5,scoring='r2').mean()
linears=cross_val_score( linear,X,y,cv=5,scoring='r2').mean()
ridge.append(regs)
lr.append(linears)
plt.plot(alpharange,ridge,color="red",label="Ridge")
plt.plot(alpharange,lr,color="blue",label="LR")
plt.legend()
plt.show()
Ridge專門的選擇最好alpha的交叉驗證
class sklearn. linear_model. Ridgecv(alphas=(0.1,1.0,10.0), fit
intercept=True, normalize=False,scoring=None,cv=None,store_cv _values=False)
from sklearn.linear_model import RidgeCV
Ridge_=RidgeCV(alphas=np. arange(1,1001,100)
#, scoring="neg_mean_squared_error"
, store_cv_values=True
#, cv=5
). fit(X,y)
#不交叉驗證的結(jié)果
Ridge_.score(X,y)
#每個alpha下的結(jié)果
Ridge_.cv_values_.mean(axis=0)
# 選擇的最佳值
Ridge_.alpha_
多項式回歸
普遍的用于解決"線性回歸只能處理線性數(shù)據(jù)"問題的手段
class sklearn.preprocessing.Po1ynomialFeatures(degree=2,
interaction_only=False, include_bias=True)
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
d=5#多項式維度
rnd=np.random.RandomState(40)#設(shè)置隨機數(shù)種子
X = rnd.uniform(-3, 3, size=100) #random.uniform,從輸入的任意兩個整數(shù)中取出size個隨機數(shù)
#生成y的思路:先使用NumPy中的函數(shù)生成一個sin函數(shù)圖像情竹,然后再人為添加噪音
y = np.sin(X) + rnd.normal(size=len(X)) / 3 #random.normal藐不,生成size個服從正態(tài)分布的隨機數(shù)
X = X.reshape(-1, 1)
line = np.linspace(-3, 3, 1000, endpoint=False).reshape(-1, 1)#測試集數(shù)據(jù)
line_=PolynomialFeatures(degree=d).fit_transform(line)
LinearR = LinearRegression().fit(X, y)
X_=PolynomialFeatures(degree=d).fit_transform(X)#對數(shù)據(jù)進行多項式處理 重要!G匦А雏蛮!
LinearR_=LinearRegression().fit(X_, y)
參考
sklearn 線性回歸_kingsure001的博客-CSDN博客_sklearn 線性回歸
機器學(xué)習(xí)sklearn-多項式回歸_kongqing23的博客-CSDN博客_sklearn多項式回歸
其他回歸模型
SVR
SVM 回歸算法稱為支持向量回歸或SVR。支持向量回歸是一種監(jiān)督學(xué)習(xí)算法阱州,用于預(yù)測離散值挑秉。支持向量回歸使用與 SVM 相同的原理。SVR 背后的基本思想是找到最佳擬合線苔货。在 SVR 中衷模,最佳擬合線是點數(shù)最多的超平面。
class sklearn.svm.SVR(*, kernel='rbf', degree=3, gamma='scale', coef0=0.0, tol=0.001, C=1.0, epsilon=0.1, shrinking=True, cache_size=200, verbose=False, max_iter=-1)
from sklearn.svm import SVR
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import numpy as np
n_samples, n_features = 10, 5
rng = np.random.RandomState(0)
y = rng.randn(n_samples)
X = rng.randn(n_samples, n_features)
regr = make_pipeline(StandardScaler(), SVR(C=1.0, epsilon=0.2))
regr.fit(X, y)
參考
機器學(xué)習(xí)筆記 - 什么是支持向量回歸(SVR)蒲赂?坐望云起的博客-CSDN博客支持向量機回歸
RandomForestRegressor
與決策樹回歸的參數(shù)類似
class sklearn.ensemble.RandomForestRegressor(n_estimators=100, *, criterion='squared_error', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=1.0, max_leaf_nodes=None, min_impurity_decrease=0.0, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, ccp_alpha=0.0, max_samples=None)
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import make_regression
X, y = make_regression(n_features=4, n_informative=2,
random_state=0, shuffle=False)
regr = RandomForestRegressor(max_depth=2, random_state=0)
regr.fit(X, y)
print(regr.predict([[0, 0, 0, 0]]))
參考
sklearn.ensemble.RandomForestRegressor
神經(jīng)網(wǎng)絡(luò)-回歸
*class *sklearn.neural_network.MLPRegressor(*hidden_layer_sizes=(100,)*, *activation='relu'*, ***, *solver='adam'*, *alpha=0.0001*, *batch_size='auto'*, *learning_rate='constant'*, *learning_rate_init=0.001*, *power_t=0.5*, *max_iter=200*, *shuffle=True*, *random_state=None*, *tol=0.0001*, *verbose=False*, *warm_start=False*, *momentum=0.9*, *nesterovs_momentum=True*, *early_stopping=False*, *validation_fraction=0.1*, *beta_1=0.9*, *beta_2=0.999*, *epsilon=1e-08*, *n_iter_no_change=10*, *max_fun=15000*)[[source]](https://github.com/scikit-learn/scikit-learn/blob/36958fb24/sklearn/neural_network/_multilayer_perceptron.py#L1266) [](https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPRegressor.html#sklearn.neural_network.MLPRegressor "Permalink to this definition")
data_ = [
[ -0.017612,14.053064,14.035452],[ -1.395634, 4.662541, 3.266907],[ -0.752157, 6.53862,5.786463],[ -1.322371, 7.152853, 5.830482],
[0.423363,11.054677,11.47804 ],[0.406704, 7.067335, 7.474039],[0.667394,12.741452,13.408846],[ -2.46015,6.866805, 4.406655],
[0.569411, 9.548755,10.118166],[ -0.026632,10.427743,10.401111],[0.850433, 6.920334, 7.770767],[1.347183,13.1755,14.522683],
[1.176813, 3.16702,4.343833],[ -1.781871, 9.097953, 7.316082],[ -0.566606, 5.749003, 5.182397],[0.931635, 1.589505, 2.52114 ],
[ -0.024205, 6.151823, 6.127618],[ -0.036453, 2.690988, 2.654535],[ -0.196949, 0.444165, 0.247216],[1.014459, 5.754399, 6.768858],
[1.985298, 3.230619, 5.215917],[ -1.693453,-0.55754, -2.250993],[ -0.576525,11.778922,11.202397],[ -0.346811,-1.67873, -2.025541],
[ -2.124484, 2.672471, 0.547987],[1.217916, 9.597015,10.814931],[ -0.733928, 9.098687, 8.364759],[1.416614, 9.619232,11.035846],
[1.38861,9.341997,10.730607],[0.317029,14.739025,15.056054]
]
data1 = np.array(data_)
print(data1)
X = data1[:, 0:2]
Y = data1[:, 2]
scaler = StandardScaler() # 標準化轉(zhuǎn)換
scaler.fit(X) # 訓(xùn)練標準化對象
X = scaler.transform(X) # 轉(zhuǎn)換數(shù)據(jù)集
clf = MLPRegressor(solver='lbfgs',alpha=1e-5, hidden_layer_sizes=(5,2), random_state=1)
clf.fit(X,Y)
pred = clf.predict([[0.317029, 14.739025]])
print('回歸預(yù)測結(jié)果:', pred)
[[-0.017612 14.053064 14.035452]
[-1.395634 4.662541 3.266907]
[-0.752157 6.53862 5.786463]
[-1.322371 7.152853 5.830482]
[ 0.423363 11.054677 11.47804 ]
[ 0.406704 7.067335 7.474039]
[ 0.667394 12.741452 13.408846]
[-2.46015 6.866805 4.406655]
[ 0.569411 9.548755 10.118166]
[-0.026632 10.427743 10.401111]
[ 0.850433 6.920334 7.770767]
[ 1.347183 13.1755 14.522683]
[ 1.176813 3.16702 4.343833]
[-1.781871 9.097953 7.316082]
[-0.566606 5.749003 5.182397]
[ 0.931635 1.589505 2.52114 ]
[-0.024205 6.151823 6.127618]
[-0.036453 2.690988 2.654535]
[-0.196949 0.444165 0.247216]
[ 1.014459 5.754399 6.768858]
[ 1.985298 3.230619 5.215917]
[-1.693453 -0.55754 -2.250993]
[-0.576525 11.778922 11.202397]
[-0.346811 -1.67873 -2.025541]
[-2.124484 2.672471 0.547987]
[ 1.217916 9.597015 10.814931]
[-0.733928 9.098687 8.364759]
[ 1.416614 9.619232 11.035846]
[ 1.38861 9.341997 10.730607]
[ 0.317029 14.739025 15.056054]]
回歸預(yù)測結(jié)果: [24.30993116]
聚類
K-means
k均值聚類算法(k-means clustering algorithm)是一種迭代求解的聚類分析算法阱冶,其步驟是,預(yù)將數(shù)據(jù)分為K組滥嘴,則隨機選取K個對象作為初始的聚類中心木蹬,然后計算每個對象與各個種子聚類中心之間的距離,把每個對象分配給距離它最近的聚類中心若皱。聚類中心以及分配給它們的對象就代表一個聚類镊叁。每分配一個樣本,聚類的聚類中心會根據(jù)聚類中現(xiàn)有的對象被重新計算走触。這個過程將不斷重復(fù)直到滿足某個終止條件晦譬。終止條件可以是沒有(或最小數(shù)目)對象被重新分配給不同的聚類,沒有(或最小數(shù)目)聚類中心再發(fā)生變化互广,誤差平方和局部最小敛腌。
*class *sklearn.cluster.KMeans(*n_clusters=8*, ***, *init='k-means++'*, *n_init=10*, *max_iter=300*, *tol=0.0001*, *verbose=0*, *random_state=None*, *copy_x=True*, *algorithm='lloyd'*)[[source]](https://github.com/scikit-learn/scikit-learn/blob/36958fb24/sklearn/cluster/_kmeans.py#L1126) [](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans "Permalink to this definition")
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
plt.figure(figsize=(12, 12))
n_samples = 1500
random_state = 170
X, y = make_blobs(n_samples=n_samples, random_state=random_state)
# Incorrect number of clusters
y_pred = KMeans(n_clusters=2, random_state=random_state).fit_predict(X)
plt.subplot(221)
plt.scatter(X[:, 0], X[:, 1], c=y_pred)
plt.title("Incorrect Number of Blobs")
# Anisotropicly distributed data
transformation = [[0.60834549, -0.63667341], [-0.40887718, 0.85253229]]
X_aniso = np.dot(X, transformation)
y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_aniso)
plt.subplot(222)
plt.scatter(X_aniso[:, 0], X_aniso[:, 1], c=y_pred)
plt.title("Anisotropicly Distributed Blobs")
# Different variance
X_varied, y_varied = make_blobs(
n_samples=n_samples, cluster_std=[1.0, 2.5, 0.5], random_state=random_state
)
y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_varied)
plt.subplot(223)
plt.scatter(X_varied[:, 0], X_varied[:, 1], c=y_pred)
plt.title("Unequal Variance")
# Unevenly sized blobs
X_filtered = np.vstack((X[y == 0][:500], X[y == 1][:100], X[y == 2][:10]))
y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_filtered)
plt.subplot(224)
plt.scatter(X_filtered[:, 0], X_filtered[:, 1], c=y_pred)
plt.title("Unevenly Sized Blobs")
plt.show()