cross_val_score 交叉驗證與 K折交叉驗證,嗯都是抄來的,自己作個參考


因為sklearn cross_val_score 交叉驗證,這個函數沒有洗牌功能,添加K 折交叉驗證,可以用來選擇模型,也可以用來選擇特征
sklearn.model_selection.cross_val_score(estimator, X, y=None, groups=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch=‘2*n_jobs’)

這里的cv 可以用下面的kf

關於scoring 參數問題

image.png

如果兩者都要求高,那就需要保證較高的F1 score

回歸類(Regression)問題中

比較常用的是 'neg_mean_squared_error‘ 也就是 均方差回歸損失

該統計參數是預測數據和原始數據對應點誤差的平方和的均值

img公式長這樣,了解下就ok了

K折交叉驗證:sklearn.model_selection.KFold(n_splits=3, shuffle=False, random_state=None)

n_splits:表示划分幾等份

shuffle:在每次划分時,是否進行洗牌

random_state:隨機種子數

屬性:

①get_n_splits(X=None, y=None, groups=None):獲取參數n_splits的值

②split(X, y=None, groups=None):將數據集划分成訓練集和測試集,返回索引生成器

通過一個不能均等划分的栗子,設置不同參數值,觀察其結果

①設置shuffle=False,運行兩次,發現兩次結果相同

from sklearn.model_selection import KFold
   ...: import numpy as np
        # np.arange(起始,終點,步長)
        # np.reshape() 是數組對象中的方法,用於改變數組的形狀  這里是12維,每組兩個元素
   ...: X = np.arange(24).reshape(12,2)
   ...: y = np.random.choice([1,2],12,p=[0.4,0.6])
   ...: kf = KFold(n_splits=5,shuffle=False)
   ...: for train_index , test_index in kf.split(X):
   ...:     print('train_index:%s , test_index: %s ' %(train_index,test_index))
----------------------------------------------------------------   

train_index:[ 3  4  5  6  7  8  9 10 11] , test_index: [0 1 2]
train_index:[ 0  1  2  6  7  8  9 10 11] , test_index: [3 4 5]
train_index:[ 0  1  2  3  4  5  8  9 10 11] , test_index: [6 7]
train_index:[ 0  1  2  3  4  5  6  7 10 11] , test_index: [8 9]
train_index:[0 1 2 3 4 5 6 7 8 9] , test_index: [10 11]

        
shuffle=True

train_index:[ 0  1  2  3  4  5  7  8 11] , test_index: [ 6  9 10]
train_index:[ 2  3  4  5  6  8  9 10 11] , test_index: [0 1 7]
train_index:[ 0  1  3  5  6  7  8  9 10 11] , test_index: [2 4]
train_index:[ 0  1  2  3  4  6  7  9 10 11] , test_index: [5 8]
train_index:[ 0  1  2  4  5  6  7  8  9 10] , test_index: [ 3 11]

n_splits 屬性值獲取方式

image.png

image.png

image.png

這里的cv 可以是cv


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM