<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Keras入門(八)K折交叉驗證

          共 2911字,需瀏覽 6分鐘

           ·

          2021-01-26 16:02

          ? ? ? ? 在文章Keras入門(一)搭建深度神經(jīng)網(wǎng)絡(DNN)解決多分類問題中,筆者介紹了如何搭建DNN模型來解決IRIS數(shù)據(jù)集的多分類問題。
          ??本文將在此基礎上介紹如何在Keras中實現(xiàn)K折交叉驗證。

          什么是K折交叉驗證?

          ??K折交叉驗證是機器學習中的一個專業(yè)術語,它指的是將原始數(shù)據(jù)隨機分成K份,每次選擇K-1份作為訓練集,剩余的1份作為測試集。交叉驗證重復K次,取K次準確率的平均值作為最終模型的評價指標。一般取K=10,即10折交叉驗證,如下圖所示:

          ??用交叉驗證的目的是為了得到可靠穩(wěn)定的模型。K折交叉驗證能夠有效提高模型的學習能力,類似于增加了訓練樣本數(shù)量,使得學習的模型更加穩(wěn)健,魯棒性更強。選擇合適的K值能夠有效避免過擬合。

          Keras實現(xiàn)K折交叉驗證

          ??我們?nèi)圆捎梦恼翶eras入門(一)搭建深度神經(jīng)網(wǎng)絡(DNN)解決多分類問題中的模型,如下:

          同時,我們對IRIS數(shù)據(jù)集采用10折交叉驗證,完整的實現(xiàn)代碼如下:

          # -*- coding: utf-8 -*-
          # model_train.py
          # Python 3.6.8, TensorFlow 2.3.0, Keras 2.4.3
          # 導入模塊
          import keras as K
          import pandas as pd
          from sklearn.model_selection import KFold


          # 讀取CSV數(shù)據(jù)集
          # 該函數(shù)的傳入?yún)?shù)為csv_file_path: csv文件路徑
          def load_data(sv_file_path):
          iris = pd.read_csv(sv_file_path)
          target_var = 'class' # 目標變量
          # 數(shù)據(jù)集的特征
          features = list(iris.columns)
          features.remove(target_var)
          # 目標變量的類別
          Class = iris[target_var].unique()
          # 目標變量的類別字典
          Class_dict = dict(zip(Class, range(len(Class))))
          # 增加一列target, 將目標變量轉(zhuǎn)化為類別變量
          iris['target'] = iris[target_var].apply(lambda x: Class_dict[x])

          return features, 'target', iris


          # 創(chuàng)建模型
          def create_model():
          init = K.initializers.glorot_uniform(seed=1)
          simple_adam = K.optimizers.Adam()
          model = K.models.Sequential()
          model.add(K.layers.Dense(units=5, input_dim=4, kernel_initializer=init, activation='relu'))
          model.add(K.layers.Dense(units=6, kernel_initializer=init, activation='relu'))
          model.add(K.layers.Dense(units=3, kernel_initializer=init, activation='softmax'))
          model.compile(loss='sparse_categorical_crossentropy', optimizer=simple_adam, metrics=['accuracy'])
          return model


          def main():
          # 1. 讀取CSV數(shù)據(jù)集
          print("Loading Iris data into memory")
          n_split = 10
          features, target, data = load_data("./iris_data.csv")
          x = data[features]
          y = data[target]
          avg_accuracy = 0
          avg_loss = 0
          for train_index, test_index in KFold(n_split).split(x):
          print("test index: ", 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]

          print("create model and train model")
          model = create_model()
          model.fit(x_train, y_train, batch_size=1, epochs=80, verbose=0)

          print('Model evaluation: ', model.evaluate(x_test, y_test))
          avg_accuracy += model.evaluate(x_test, y_test)[1]
          avg_loss += model.evaluate(x_test, y_test)[0]

          print("K fold average accuracy: {}".format(avg_accuracy / n_split))
          print("K fold average accuracy: {}".format(avg_loss / n_split))


          main()

          模型的輸出結果如下:

          Iterationlossaccuracy
          10.000561.0
          20.000211.0
          30.000221.0
          40.006081.0
          50.219250.8667
          60.523900.8667
          70.009981.0
          80.044311.0
          90.145901.0
          100.212860.8667
          avg0.116330.9600

          10折交叉驗證的平均loss為0.11633,平均準確率為96.00%。

          總結

          ??本文代碼已存放至Github,網(wǎng)址為:https://github.com/percent4/Keras-K-fold-test 。
          ??感謝大家的閱讀~
          ??2020.1.24于上海浦東


          瀏覽 157
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  操BAV网 | 久久伊人免费 | 91久色| 大尺度视频在线 | 口爆在线|