<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>

          100天搞定機器學(xué)習(xí):寫YAML配置文件

          共 5590字,需瀏覽 12分鐘

           ·

          2021-04-09 14:23

          ↑↑↑點擊上方藍字,回復(fù)資料,10個G的驚喜

          100天搞定機器學(xué)習(xí)|Day1-62 合集

          大家好,我是老胡

          編程中免不了要寫配置文件,今天繼續(xù)100天搞定機器學(xué)習(xí)的番外學(xué)習(xí)一個比 JSON 更簡潔和強大的語言————YAML 。文簡單介紹 YAML 的語法和用法,以及 YAML 在機器學(xué)習(xí)項目中的應(yīng)用實例。歡迎大家一起學(xué)習(xí),也歡迎點贊、在看、分享!

          另:yaml的妙用不限于本篇,我會在后續(xù)的Python網(wǎng)絡(luò)編程專欄再做介紹。

          YAML

          YAML 是 "YAML Ain't a Markup Language"(YAML 不是一種標記語言)的遞歸縮寫。YAML 的語法和其他高級語言類似,并且可以簡單表達清單、散列表,標量等數(shù)據(jù)形態(tài)。它使用空白符號縮進和大量依賴外觀的特色,特別適合用來表達或編輯數(shù)據(jù)結(jié)構(gòu)、各種配置文件、傾印調(diào)試內(nèi)容、文件大綱。YAML 的配置文件后綴為 .yaml

          YAML 它的基本語法規(guī)則如下:

          • 大小寫敏感
          • 使用縮進表示層級關(guān)系
          • 縮進時不允許使用Tab鍵,只允許使用空格。
          • 縮進的空格數(shù)目不重要,只要相同層級的元素左側(cè)對齊即可
          • #號 表示注釋

          YAML 支持的數(shù)據(jù)結(jié)構(gòu)有三種:

          • 對象:鍵值對的集合,對象鍵值對使用冒號結(jié)構(gòu)表示 key: value,冒號后面要加一個空格。
          • 數(shù)組:一組按次序排列的值,又稱為序列/ 列表,用 - 表示。
          • 純量(scalars):單個的、不可再分的值

          YAML 用法

          安裝

          pip install pyyaml

          yaml 文件格式很簡單,比如:

          # categories.yaml file

          sports: #注意,冒號后面要加空格

            - soccer # 數(shù)組
            - football
            - basketball
            - cricket
            - hockey
            - table tennis

          countries: 

            - Pakistan
            - USA
            - India
            - China
            - Germany
            - France
            - Spain

          python 讀取 yaml 文件

          # read_categories.py file

          import yaml

          with open(r'categories.yaml') as file:
              documents = yaml.full_load(file)

              for item, doc in documents.items():
                  print(item, ":", doc)

          運行結(jié)果:

          sports : ['soccer''football''basketball''cricket''hockey''table tennis']
          countries : ['Pakistan''USA''India''China''Germany''France''Spain']

          以上便是 YAML 最基礎(chǔ)的應(yīng)用了,可能大家還是有點一頭霧水,咱們更進一步,看看在機器學(xué)習(xí)項目中如何寫 YAML 配置文件。

          YAML & Machine Learning

          我們直接改寫100天搞定機器學(xué)習(xí)|Day62 隨機森林調(diào)參實戰(zhàn)中的代碼。

          Project structure

          寫配置文件rf_config.yaml

          #INITIAL SETTINGS
          data_directory: ./data/
          data_name: creditcard.csv
          target_name: Class
          test_size: 0.3
          model_directory: ./models/
          model_name: RF_classifier.pkl


          #RF parameters
          n_estimators: 50
          max_depth: 6
          min_samples_split: 5
          oob_score: True
          random_state: 666
          n_jobs: 2

          完整代碼,可以對比源代碼看看區(qū)別:

          # rf_with_yaml_file.py
          import os
          import yaml
          import joblib
          import numpy as np
          import pandas as pd
          from sklearn.model_selection import train_test_split
          from sklearn.ensemble import RandomForestClassifier
          from sklearn.metrics import roc_auc_score

          CONFIG_PATH = "./config/"


          def load_config(config_name):
              with open(os.path.join(CONFIG_PATH, config_name)) as file:
                  config = yaml.safe_load(file)

              return config


          config = load_config("rf_config.yaml")

          df = pd.read_csv(os.path.join(config["data_directory"], config["data_name"]))
          data = df.iloc[:, 1:31]


          X = data.loc[:, data.columns != config["target_name"]]
          y = data.loc[:, data.columns == config["target_name"]]

          number_records_fraud = len(data[data.Class == 1])
          fraud_indices = np.array(data[data.Class == 1].index)
          normal_indices = data[data.Class == 0].index
          random_normal_indices = np.random.choice(
              normal_indices, number_records_fraud, replace=False)
          random_normal_indices = np.array(random_normal_indices)
          under_sample_indices = np.concatenate(
              [fraud_indices, random_normal_indices])
          under_sample_data = data.iloc[under_sample_indices, :]
          X_undersample = under_sample_data.loc[:,
                                                under_sample_data.columns != config["target_name"]]
          y_undersample = under_sample_data.loc[:,
                                                under_sample_data.columns == config["target_name"]]

          X_train, X_test, y_train, y_test = train_test_split(
              X, y, test_size=config["test_size"], random_state=42
          )


          rf1 = RandomForestClassifier(
              n_estimators=config["n_estimators"],
              max_depth=config["max_depth"],
              min_samples_split=config["min_samples_split"],
              oob_score=config["oob_score"],
              random_state=config["random_state"],
              n_jobs=config["n_jobs"]
          )

          rf1.fit(X_train, y_train)
          print(rf1.oob_score_)
          y_predprob1 = rf1.predict_proba(X_test)[:, 1]
          print("AUC Score (Train): %f" % roc_auc_score(y_test, y_predprob1))

          joblib.dump(rf1, os.path.join(config["model_directory"], config["model_name"]))

          reference

          https://www.runoob.com/w3cnote/yaml-intro.html
          https://www.ruanyifeng.com/blog/2016/07/yaml.html

          也可以加一下老胡的微信
          圍觀朋友圈~~~


          推薦閱讀

          (點擊標題可跳轉(zhuǎn)閱讀)

          論機器學(xué)習(xí)領(lǐng)域的內(nèi)卷

          機器學(xué)習(xí)博士自救指南

          機器學(xué)習(xí)必知必會的 6 種神經(jīng)網(wǎng)絡(luò)類型

          你見過的最全面的Python重點知識匯總

          老鐵,三連支持一下,好嗎?↓↓↓

          瀏覽 93
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

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

          手機掃一掃分享

          分享
          舉報
          <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>
                  中文字幕在线字幕中文乱码区别 | 黄视频在线观看免费 | 黄色电影中文字幕在线观看 | 国产三级豆花 | 青青操久久 |