Ludwig中文教程

Ludwig 中文教程

翻譯自:
https://ludwig-ai.github.io/ludwig-docs/getting_started/
https://ludwig-ai.github.io/ludwig-docs/examples/

github地址:
https://github.com/liafuzho/ludwig-tutor-cn

入門

簡介

Ludwig 是一個工具箱核芽,它允許用戶訓(xùn)練和測試深度學(xué)習(xí)模型戏自,而不需要編寫代碼役首。它建立在 TensorFlow 之上战得。

為了訓(xùn)練您的模型傅瞻,您必須提供一個包含您數(shù)據(jù)的文件梯澜,一個“列”列表作為輸入婿失,另外一個“列”列表作為輸出享幽,Ludwig 將完成剩下的工作睹限。簡單的命令可以本地也可以分布式地去訓(xùn)練模型譬猫,并使用它們來預(yù)測新數(shù)據(jù)讯檐。

您也可以使用 Python 的 Ludwig 編程接口。一套可視化工具允許您分析模型的訓(xùn)練和測試其性能染服,并對他們進(jìn)行比較别洪。

Ludwig 是基于可擴展性原則構(gòu)建的,并且基于抽象的數(shù)據(jù)類型柳刮,不但可以輕松添加新的數(shù)據(jù)類型挖垛,而且對添加新的模型架構(gòu)也變得非常容易。

它可以使從業(yè)人員用來做快速訓(xùn)練并且測試深度學(xué)習(xí)模型秉颗,也可以讓研究人員通過實驗設(shè)置痢毒,執(zhí)行相同的數(shù)據(jù)處理和評估來獲得強勁可靠的比較基準(zhǔn)。

Ludwig 提供了一組模型架構(gòu)蚕甥,可以組合在一起為給定的用例創(chuàng)建端到端的模型哪替。打個比方,如果深度學(xué)習(xí)函數(shù)庫為您的建筑物提供了構(gòu)建模塊梢灭, Ludwig 則為您的城市提供了建筑物夷家。您可以從可用的建筑物中進(jìn)行選擇,或者將自己的建筑物添加進(jìn)來使其可用敏释。

工具箱中的核心設(shè)計原則是:-不需要編碼: 不需要編碼技能來訓(xùn)練模型并使用它來獲得預(yù)測库快。通用性: 一種新的基于數(shù)據(jù)類型的深度學(xué)習(xí)模型設(shè)計方法使得該工具可以跨越許多不同的用例使用。- 靈活性: 經(jīng)驗豐富的用戶可以廣泛的控制模型構(gòu)建和訓(xùn)練钥顽,而新手將發(fā)現(xiàn)它易于使用义屏。擴展性: 可以輕松添加新的模型架構(gòu)和新的數(shù)據(jù)類型》浯螅可理解性: 深度學(xué)習(xí)模型內(nèi)部通常被認(rèn)為是黑箱闽铐,但是 Ludwig 提供標(biāo)準(zhǔn)的可視化工具來理解它們的性能并比較它們的預(yù)測。- 開源: Apache License 2.0

安裝

Ludwig 要求您使用 python3.6+ 奶浦,如果您沒有安裝 python3兄墅,可以通過運行以下命令來安裝:

sudo apt install python3  # on ubuntu
brew install python3      # on mac

您可能想虛擬一個單獨的 Python 環(huán)境。

virtualenv -p python3 venv

安裝 Ludwig 只需運行:

pip install ludwig

這將只安裝基本的 Ludwig澳叉,不同的需求類型有著不同的依賴關(guān)系隙咸。我們將它們分為不同的附加組件,這樣用戶僅僅只安裝他們真正需要的組件:-ludwig[text] 為文本依賴成洗。-ludwig[audio] 為音頻和語音的依賴五督。-ludwig[image] 為圖像依賴。-ludwig[hyperopt] 為超參數(shù)優(yōu)化依賴瓶殃。-ludwig[horovod] 為分布式訓(xùn)練依賴充包。-ludwig[serve] 為服務(wù)依賴。-ludwig[viz] 為可視化依賴遥椿。-ludwig[test] 為測試依賴基矮。

支持 Horovod 分布式訓(xùn)練淆储, 可以通過 pip install ludwig[horovod]HOROVOD_GPU_OPERATIONS=NCCL pip install ludwig[horovod] 用于 GPU 支持。詳情請參閱 Horovod 的安裝指南愈捅,了解可用的安裝選項遏考。

可以使用 pip install ludwig[extra1,extra2,...] 同時安裝任何額外的包慈鸠,例如 pip install ludwig[text,viz]蓝谨。完整的依賴關(guān)系集可以通過 pip install ludwig[full] 安裝。

希望從源代碼構(gòu)建的開發(fā)人員:

git clone git@github.com:ludwig-ai/ludwig.git
cd ludwig
virtualenv -p python3 venv
source venv/bin/activate
pip install -e '.[test]'

注意: 如果您不使用 GPUs 運行青团,那么您可能希望使用僅支持 cpu 的 TensorFlow 版本譬巫,它占用的磁盤空間要少得多。要使用只支持 cpu 的 TensorFlow 版本督笆,請卸載 TensorFlow 并在安裝 Ludwig 后用 TensorFlow-cpu 替換它芦昔。請確保在 requirements.txt 所示的兼容范圍內(nèi)安裝一個版本。

注意:如果您不使用 GPU 運行娃肿,只想使用 CPU 版本的 TensorFlow咕缎, 它占用的磁盤空間則要少得多。要使用只支持 CPU 的 TensorFlow 版本料扰, 請卸載 TensorFlow 并在安裝 Ludwig 后用 tensorflow-cpu 替換它凭豪。請確保在 requirements.txt 所示的兼容范圍內(nèi)安裝一個版本。

基本原則

Ludwig 提供了三個主要功能:訓(xùn)練模型和使用他們來預(yù)測和評估晒杈。它基于抽象的數(shù)據(jù)類型嫂伞,因此將對共有數(shù)據(jù)類型的不同數(shù)據(jù)集執(zhí)行相同的數(shù)據(jù)預(yù)處理和后處理,并且開發(fā)的相同編碼和解碼模型可以在多個任務(wù)中重復(fù)使用拯钻。

在 Ludwig 中訓(xùn)練一個模型非常簡單: 您提供一個數(shù)據(jù)集文件和一個 YAML 文件定義的模型帖努。

模型定義包含一個輸入列的列表和一個輸出列的列表,您所要做的就是指定數(shù)據(jù)集中作為輸入到模型的列的名稱以及它們的數(shù)據(jù)類型粪般,還有數(shù)據(jù)集中作為輸出的列的名稱拼余,模型將學(xué)會預(yù)測的目標(biāo)變量。Ludwig 將為此構(gòu)建一個深度學(xué)習(xí)模型亩歹,并為您訓(xùn)練它匙监。

目前,Ludwig 中可用的數(shù)據(jù)類型是:

  • binary
  • numerical
  • category
  • set
  • bag
  • sequence
  • text
  • timeseries
  • image
  • audio
  • date
  • h3
  • vector

通過為輸入和輸出選擇不同的數(shù)據(jù)類型捆憎,用戶可以解決許多不同的任務(wù)舅柜,例如:

  • text input + category output = text classifier【文本分類】
  • image input + category output = image classifier【圖像分類】
  • image input + text output = image captioning【圖像描述】
  • audio input + binary output = speaker verification【語音驗證】
  • text input + sequence output = named entity recognition / summarization【命名實體識別/摘要】
  • category, numerical and binary inputs + numerical output = regression【回歸】
  • timeseries input + numerical output = forecasting model【預(yù)測模型】
  • category, numerical and binary inputs + binary output = fraud detection【欺詐檢測】

看看示例,了解如何使用 Ludwig 用于更多的任務(wù)躲惰。

模型定義可以包含額外的信息致份,特別是如何預(yù)處理數(shù)據(jù)中的每一列,為每一列使用哪個編碼器和解碼器础拨,架構(gòu)和訓(xùn)練參數(shù)氮块,超參數(shù)進(jìn)行優(yōu)化绍载。這使得新手可以輕松使用,專家可以靈活使用滔蝉。

訓(xùn)練

例如击儡,給定一個下面所示的文本分類數(shù)據(jù)集:

doc_text class
Former president Barack Obama ... politics
Juventus hired Cristiano Ronaldo ... sport
LeBron James joins the Lakers ... sport
... ...

您希望學(xué)習(xí)一個使用 doc _ text 列的內(nèi)容作為輸入來預(yù)測 class 列中的值的模型。您可以使用下面的模型定義:

{input_features: [{name: doc_text, type: text}], output_features: [{name: class, type: category}]}

然后在控制臺輸入以下命令開始訓(xùn)練:

ludwig train --dataset path/to/file.csv --config "{input_features: [{name: doc_text, type: text}], output_features: [{name: class, type: category}]}"

其中 path/to/file.csv 是 UTF-8 編碼的 CSV 文件的路徑蝠引,該文件包含先前表中的數(shù)據(jù)集(許多其他的數(shù)據(jù)格式也支持)阳谍。Ludwig 將:

  1. 執(zhí)行數(shù)據(jù)的隨機分割。
  2. 預(yù)處理數(shù)據(jù)集螃概。
  3. 構(gòu)建一個 ParallelCNN 模型(文本的默認(rèn)模型) 矫夯,該模型通過 softmax 分類器解碼輸出分類。
  4. 在訓(xùn)練集上訓(xùn)練模型吊洼,直到驗證集上的性能停止提升训貌。

訓(xùn)練進(jìn)度將顯示在控制臺,但 TensorBoard 也可以使用冒窍。

如果您更喜歡使用 RNN 編碼器并增加要訓(xùn)練的周期數(shù)递沪,您所要做的就是將模型定義改為:

{input_features: [{name: doc_text, type: text, encoder: rnn}], output_features: [{name: class, type: category}], training: {epochs: 50}}

請參考使用手冊,找出模型定義中可用的所有選項综液,并查看示例款慨,了解如何將 Ludwig 用于幾個不同的任務(wù)。

訓(xùn)練結(jié)束后意乓,Ludwig 將創(chuàng)建一個 results 目錄樱调,其中包含訓(xùn)練模型及其超參數(shù)和訓(xùn)練過程的統(tǒng)計摘要。您可以使用 visualize 工具中的幾個可視化選項之一來可視化它們届良,例如:

ludwig visualize --visualization learning_curves --training_statistics path/to/training_statistics.json

這個命令將顯示一個如下圖所示的圖形笆凌,在這里您可以看到在訓(xùn)練過程中的損失和準(zhǔn)確性:

還有幾個可視化效果可用,請參考可視化以獲得更多細(xì)節(jié)士葫。

分布式訓(xùn)練

您可以使用 Horovod 分布式訓(xùn)練乞而,它允許在具有多個 GPUs 的單臺機器上以及在具有多個 GPUs 的多臺機器上進(jìn)行培訓(xùn)。詳情請參閱使用手冊慢显。

預(yù)測與評估

如果您想讓以前訓(xùn)練過的模型預(yù)測新數(shù)據(jù)的目標(biāo)輸出值爪模,您可在控制臺輸入以下命令:

ludwig predict --dataset path/to/data.csv --model_path /path/to/model

運行這個命令將返回模型預(yù)測。

如果數(shù)據(jù)集還包含目標(biāo)輸出的正確標(biāo)注荚藻,則可以將它們與從模型獲得的預(yù)測進(jìn)行比較屋灌,以評估模型性能。

ludwig evaluate --dataset path/to/data.csv --model_path /path/to/model

這將產(chǎn)生評估性能統(tǒng)計數(shù)據(jù)应狱,可以通過可視化工具進(jìn)行可視化共郭,也可用于比較不同模型的性能和其預(yù)測,例如:

ludwig visualize --visualization compare_performance --test_statistics path/to/test_statistics_model_1.json path/to/test_statistics_model_2.json

將返回一個不同指標(biāo)的模型比較條形圖:

一個方便的 ludwig experiment 命令,可以依次進(jìn)行訓(xùn)練和預(yù)測除嘹。

編程接口

Ludwig 還提供了一個簡單的編程接口写半,允許您訓(xùn)練或加載模型,并使用它獲取對新數(shù)據(jù)的預(yù)測:

from ludwig.api import LudwigModel

# train a model
config = {...}
model = LudwigModel(config)
train_stats = model.train(training_data)

# or load a model
model = LudwigModel.load(model_path)

# obtain predictions
predictions = model.predict(test_data)

config 包含提供給命令行的 YAML 文件的相同信息尉咕。更多的細(xì)節(jié)在使用手冊和接口文檔中提供叠蝇。

可擴展性

Ludwig 是在考慮可擴展性的基礎(chǔ)上建立起來的。通過添加特定于數(shù)據(jù)類型的抽象類實現(xiàn)(包含預(yù)處理年缎、編碼和解碼數(shù)據(jù)的函數(shù)) 悔捶,可以很容易地添加目前不支持的附加數(shù)據(jù)類型。

此外晦款,通過實現(xiàn)一個接受張量(根據(jù)數(shù)據(jù)類型炎功,具有特定等級)作為輸入并提供張量作為輸出的類,可以很容易地添加具有特定超參數(shù)的新模型缓溅。這鼓勵重用和與社區(qū)共享新的模型。更多細(xì)節(jié)請參考開發(fā)人員指南赁温。

示例

本節(jié)包含幾個示例坛怪,展示如何使用 Ludwig 為各種任務(wù)構(gòu)建模型。對于每個任務(wù)股囊,我們都顯示一個示例數(shù)據(jù)集和一個示例模型定義袜匿,可以使用這些數(shù)據(jù)來訓(xùn)練模型。

文本分類

這個例子展示了如何用 Ludwig 構(gòu)建一個文本分類器稚疹。它可以使用 Reuters-21578 數(shù)據(jù)集執(zhí)行居灯,特別是在 CMU's Text Analytics course website 上的版本。同一個網(wǎng)頁上的其他數(shù)據(jù)集内狗,比如 OHSUMED怪嫌,是一個著名的醫(yī)學(xué)摘要數(shù)據(jù)集,而 Epinions.com, 網(wǎng)站柳沙,一個產(chǎn)品評論數(shù)據(jù)集岩灭,也可以使用,因為列的名稱是相同的赂鲤。

text class
Toronto Feb 26 - Standard Trustco said it expects earnings in 1987 to increase at least 15... politics
New York Feb 26 - American Express Co remained silent on market rumors... acquisition
BANGKOK March 25 - Vietnam will resettle 300000 people on state farms known as new economic... coffee
ludwig experiment \
  --dataset text_classification.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: text
        type: text
        level: word
        encoder: parallel_cnn

output_features:
    -
        name: class
        type: category

命名實體識別標(biāo)簽

utterance tag
Blade Runner is a 1982 neo-noir science fiction film directed by Ridley Scott Movie Movie O O Date O O O O O O Person Person
Harrison Ford and Rutger Hauer starred in it Person Person O Person person O O O
Philip Dick 's novel Do Androids Dream of Electric Sheep ? was published in 1968 Person Person O O Book Book Book Book Book Book Book O O O Date
ludwig experiment \
  --dataset sequence_tags.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: utterance
        type: text
        level: word
        encoder: rnn
        cell_type: lstm
        reduce_output: null
        preprocessing:
          word_tokenizer: space

output_features:
    -
        name: tag
        type: sequence
        decoder: tagger

自然語言理解

utterance intent slots
I want a pizza order_food O O O B-Food_type
Book a flight to Boston book_flight O O O O B-City
Book a flight at 7pm to London book_flight O O O O B-Departure_time O B-City
ludwig experiment \
  --dataset nlu.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: utterance
        type: text
        level: word
        encoder: rnn
        cell_type: lstm
        bidirectional: true
        num_layers: 2
        reduce_output: null
        preprocessing:
          word_tokenizer: space

output_features:
    -
        name: intent
        type: category
        reduce_input: sum
        num_fc_layers: 1
        fc_size: 64
    -
        name: slots
        type: sequence
        decoder: tagger

機器翻譯

english intent
Hello! How are you doing? Ciao, come stai?
I got promoted today Oggi sono stato promosso!
Not doing well today Oggi non mi sento bene
ludwig experiment \
  --dataset translation.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: english
        type: text
        level: word
        encoder: rnn
        cell_type: lstm
        reduce_output: null
        preprocessing:
          word_tokenizer: english_tokenize

output_features:
    -
        name: italian
        type: text
        level: word
        decoder: generator
        cell_type: lstm
        attention: bahdanau
        loss:
            type: sampled_softmax_cross_entropy
        preprocessing:
          word_tokenizer: italian_tokenize

training:
    batch_size: 96

基于 Sequence2Sequence 的聊天對話建模

user1 user2
Hello! How are you doing? Doing well, thanks!
I got promoted today Congratulations
Not doing well today I’m sorry, can I do something to help you?
ludwig experiment \
  --dataset chitchat.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: user1
        type: text
        level: word
        encoder: rnn
        cell_type: lstm
        reduce_output: null

output_features:
    -
        name: user2
        type: text
        level: word
        decoder: generator
        cell_type: lstm
        attention: bahdanau
        loss:
            type: sampled_softmax_cross_entropy

training:
    batch_size: 96

情緒分析

review sentiment
The movie was fantastic! positive
Great acting and cinematography positive
The acting was terrible! negative
ludwig experiment \
  --dataset sentiment.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: review
        type: text
        level: word
        encoder: parallel_cnn

output_features:
    -
        name: sentiment
        type: category

圖像分類

image_path class
images/image_000001.jpg car
images/image_000002.jpg dog
images/image_000003.jpg boat
ludwig experiment \
  --dataset image_classification.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: image_path
        type: image
        encoder: stacked_cnn

output_features:
    -
        name: class
        type: category

圖像分類(MNIST)

這是一個在 MNIST 數(shù)據(jù)集上訓(xùn)練圖像分類模型的完整例子噪径。

下載 MNIST 數(shù)據(jù)集

git clone https://github.com/myleott/mnist_png.git
cd mnist_png/
tar -xf mnist_png.tar.gz
cd mnist_png/

創(chuàng)建訓(xùn)練和測試 csv

在同一個目錄下打開 python shell 并運行以下命令:

import os
for name in ['training', 'testing']:
    with open('mnist_dataset_{}.csv'.format(name), 'w') as output_file:
        print('=== creating {} dataset ==='.format(name))
        output_file.write('image_path,label\n')
        for i in range(10):
            path = '{}/{}'.format(name, i)
            for file in os.listdir(path):
                if file.endswith(".png"):
                    output_file.write('{},{}\n'.format(os.path.join(path, file), str(i)))

現(xiàn)在您應(yīng)該有一個包含 60000 條訓(xùn)練數(shù)據(jù)的 mnist_dataset_training.csv 和包含 10000 條測試數(shù)據(jù)的 mnist_dataset_testing.csv,格式如下:

image_path label
training/0/16585.png 0
training/0/24537.png 0
training/0/25629.png 0

訓(xùn)練模型

在安裝 ludwig 的虛擬環(huán)境的目錄中運行以下命令:

ludwig train \
  --training_set <PATH_TO_MNIST_DATASET_TRAINING_CSV> \
  --test_set <PATH_TO_MNIST_DATASET_TEST_CSV> \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: image_path
        type: image
        encoder: stacked_cnn
        conv_layers:
            -
                num_filters: 32
                filter_size: 3
                pool_size: 2
                pool_stride: 2
            -
                num_filters: 64
                filter_size: 3
                pool_size: 2
                pool_stride: 2
                dropout: 0.4
        fc_layers:
            -
                fc_size: 128
                dropout: 0.4

output_features:
    -
        name: label
        type: category

training:
    early_stop: 5

圖像描述

image_path caption
imagenet/image_000001.jpg car driving on the street
imagenet/image_000002.jpg dog barking at a cat
imagenet/image_000003.jpg boat sailing in the ocean
ludwig experiment \
--dataset image captioning.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: image_path
        type: image
        encoder: stacked_cnn

output_features:
    -
        name: caption
        type: text
        level: word
        decoder: generator
        cell_type: lstm

單樣本學(xué)習(xí)和孿生網(wǎng)絡(luò)

可以將此示例視為 Omniglot 數(shù)據(jù)集上的單樣本學(xué)習(xí)的簡單基準(zhǔn)数初。任務(wù)是找爱,給定兩個手寫字符的圖像,識別兩個實例是否是相同字符泡孩。

image_path_1 image_path_2 similarity
balinese/character01/0108_13.png balinese/character01/0108_18.png 1
balinese/character01/0108_13.png balinese/character08/0115_12.png 0
balinese/character01/0108_04.png balinese/character01/0108_08.png 1
balinese/character01/0108_11.png balinese/character05/0112_02.png 0
ludwig experiment \
--dataset balinese_characters.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: image_path_1
        type: image
        encoder: stacked_cnn
        preprocessing:
          width: 28
          height: 28
          resize_image: true
    -
        name: image_path_2
        type: image
        encoder: stacked_cnn
        preprocessing:
          width: 28
          height: 28
          resize_image: true
        tied_weights: image_path_1

combiner:
    type: concat
    num_fc_layers: 2
    fc_size: 256

output_features:
    -
        name: similarity
        type: binary

視覺問答

image_path question answer
imdata/image_000001.jpg Is there snow on the mountains? yes
imdata/image_000002.jpg What color are the wheels blue
imdata/image_000003.jpg What kind of utensil is in the glass bowl knife
ludwig experiment \
--dataset vqa.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: image_path
        type: image
        encoder: stacked_cnn
    -
        name: question
        type: text
        level: word
        encoder: parallel_cnn

output_features:
    -
        name: answer
        type: text
        level: word
        decoder: generator
        cell_type: lstm
        loss:
            type: sampled_softmax_cross_entropy

數(shù)字語音識別

這是在 “MNIST 語音識別數(shù)據(jù)集” 上訓(xùn)練數(shù)字語音識別模型的一個完整例子车摄。

下載免費數(shù)字語音

git clone https://github.com/Jakobovski/free-spoken-digit-dataset.git
mkdir speech_recog_digit_data
cp -r free-spoken-digit-dataset/recordings speech_recog_digit_data
cd speech_recog_digit_data

創(chuàng)建一個 CSV 數(shù)據(jù)集

echo "audio_path","label" >> "spoken_digit.csv"
cd "recordings"
ls | while read -r file_name; do
   audio_path=$(readlink -m "${file_name}")
   label=$(echo ${file_name} | cut -c1)
   echo "${audio_path},${label}" >> "../spoken_digit.csv"
done
cd "../"

現(xiàn)在您 spoken_digit.csv 文件中包含了 2000 個具有以下格式的示例:

audio_path label
.../speech_recog_digit_data/recordings/0_jackson_0.wav 0
.../speech_recog_digit_data/recordings/0_jackson_10.wav 0
.../speech_recog_digit_data/recordings/0_jackson_11.wav 0
... ...
.../speech_recog_digit_data/recordings/1_jackson_0.wav 1

訓(xùn)練模型

在安裝 ludwig 的虛擬環(huán)境的目錄中運行以下命令:

ludwig experiment \
  --dataset <PATH_TO_SPOKEN_DIGIT_CSV> \
  --config_file config_file.yaml

config.yaml

input_features:
    -
        name: audio_path
        type: audio
        encoder: stacked_cnn
        preprocessing:
            audio_feature:
                type: fbank
                window_length_in_s: 0.025
                window_shift_in_s: 0.01
                num_filter_bands: 80
            audio_file_length_limit_in_s: 1.0
            norm: per_file
        reduce_output: concat
        conv_layers:
            -
                num_filters: 16
                filter_size: 6
                pool_size: 4
                pool_stride: 4
                dropout: 0.4
            -
                num_filters: 32
                filter_size: 3
                pool_size: 2
                pool_stride: 2
                dropout: 0.4
        fc_layers:
            -
                fc_size: 64
                dropout: 0.4

output_features:
    -
        name: label
        type: category

training:
    early_stop: 10

語音驗證

這個例子描述了如何使用 Ludwig 為一個簡單的說話人驗證任務(wù)。我們假設(shè)有下列數(shù)據(jù),標(biāo)簽0對應(yīng)于未授權(quán)語音的音頻文件练般,標(biāo)簽1對應(yīng)于授權(quán)語音的音頻文件矗漾。樣本數(shù)據(jù)如下:

audio_path label
audiodata/audio_000001.wav 0
audiodata/audio_000002.wav 0
audiodata/audio_000003.wav 1
audiodata/audio_000004.wav 1
ludwig experiment \
--dataset speaker_verification.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: audio_path
        type: audio
        preprocessing:
            audio_file_length_limit_in_s: 7.0
            audio_feature:
                type: stft
                window_length_in_s: 0.04
                window_shift_in_s: 0.02
        encoder: cnnrnn

output_features:
    -
        name: label
        type: binary

Kaggle's Titanic: 預(yù)測幸存者

這個例子描述了如何使用 Ludwig 為 kaggle competition 競賽訓(xùn)練一個模型,來預(yù)測乘客在泰坦尼克號災(zāi)難中生存的概率薄料。下面是數(shù)據(jù)的一個例子:

Pclass Sex Age SibSp Parch Fare Survived Embarked
3 male 22 1 0 7.2500 0 S
1 female 38 1 0 71.2833 1 C
3 female 26 0 0 7.9250 0 S
3 male 35 0 0 8.0500 0 S

完整的數(shù)據(jù)和列描述可以在這里找到敞贡。

在下載數(shù)據(jù)之后,使用 Ludwig 在這個數(shù)據(jù)集上訓(xùn)練模型,

ludwig experiment \
  --dataset <PATH_TO_TITANIC_CSV> \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: Pclass
        type: category
    -
        name: Sex
        type: category
    -
        name: Age
        type: numerical
        preprocessing:
          missing_value_strategy: fill_with_mean
    -
        name: SibSp
        type: numerical
    -
        name: Parch
        type: numerical
    -
        name: Fare
        type: numerical
        preprocessing:
          missing_value_strategy: fill_with_mean
    -
        name: Embarked
        type: category

output_features:
    -
        name: Survived
        type: binary

使用更精確的特征轉(zhuǎn)換和預(yù)處理可以獲得更好的結(jié)果摄职,但這個例子的唯一目的是展示這種類型的任務(wù)和數(shù)據(jù)如何在 Ludwig 中使用誊役。

時間序列預(yù)測

盡管直接時間序列預(yù)測尚在進(jìn)行中,但 Ludwig 可以攝取時間序列輸入特征數(shù)據(jù)并進(jìn)行數(shù)值預(yù)測谷市。下面例子是一個經(jīng)過訓(xùn)練的模型蛔垢,它可以在五個不同的層次上預(yù)測時間。

timeseries_data y1 y2 y3 y4 y5
15.07 14.89 14.45 ... 16.92 16.67 16.48 17.00 17.02
14.89 14.45 14.30 ... 16.67 16.48 17.00 17.02 16.48
14.45 14.3 14.94 ... 16.48 17.00 17.02 16.48 15.82
ludwig experiment \
--dataset timeseries_data.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: timeseries_data
        type: timeseries

output_features:
    -
        name: y1
        type: numerical
    -
        name: y2
        type: numerical
    -
        name: y3
        type: numerical
    -
        name: y4
        type: numerical
    -
        name: y5
        type: numerical

時間序列預(yù)報(天氣數(shù)據(jù)示例)

這個例子說明了使用洛杉磯的歷史溫度數(shù)據(jù)進(jìn)行單變量時間序列預(yù)測迫悠。

在 Kaggle 上下載并解壓每小時可用的歷史氣象數(shù)據(jù)
https://www.kaggle.com/selfishgene/historical-hourly-weather-data

運行下面的 python 腳本來準(zhǔn)備訓(xùn)練數(shù)據(jù):

import pandas as pd
from ludwig.utils.data_utils import add_sequence_feature_column

df = pd.read_csv(
    '<PATH_TO_FILE>/temperature.csv',
    usecols=['Los Angeles']
).rename(
    columns={"Los Angeles": "temperature"}
).fillna(method='backfill').fillna(method='ffill')

# normalize
df.temperature = ((df.temperature-df.temperature.mean()) /
                  df.temperature.std())

train_size = int(0.6 * len(df))
vali_size = int(0.2 * len(df))

# train, validation, test split
df['split'] = 0
df.loc[
    (
        (df.index.values >= train_size) &
        (df.index.values < train_size + vali_size)
    ),
    ('split')
] = 1
df.loc[
    df.index.values >= train_size + vali_size,
    ('split')
] = 2

# prepare timeseries input feature colum
# (here we are using 20 preceding values to predict the target)
add_sequence_feature_column(df, 'temperature', 20)
df.to_csv('<PATH_TO_FILE>/temperature_la.csv')
ludwig experiment \
--dataset <PATH_TO_FILE>/temperature_la.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: temperature_feature
        type: timeseries
        encoder: rnn
        embedding_size: 32
        state_size: 32

output_features:
    -
        name: temperature
        type: numerical

電影分級預(yù)測

year duration nominations categories rating
1921 3240 0 comedy drama 8.4
1925 5700 1 adventure comedy 8.3
1927 9180 4 drama comedy scifi 8.4
ludwig experiment \
--dataset movie_ratings.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: year
        type: numerical
    -
        name: duration
        type: numerical
    -
        name: nominations
        type: numerical
    -
        name: categories
        type: set

output_features:
    -
        name: rating
        type: numerical

多標(biāo)簽分類

image_path tags
images/image_000001.jpg car man
images/image_000002.jpg happy dog tie
images/image_000003.jpg boat water
ludwig experiment \
--dataset image_data.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: image_path
        type: image
        encoder: stacked_cnn

output_features:
    -
        name: tags
        type: set

多任務(wù)學(xué)習(xí)

這個例子的靈感來自 Collobert 等人的經(jīng)典論文 Natural Language Processing (Almost) from Scratch鹏漆。

sentence chunks part_of_speech named_entities
San Francisco is very foggy B-NP I-NP B-VP B-ADJP I-ADJP NNP NNP VBZ RB JJ B-Loc I-Loc O O O
My dog likes eating sausage B-NP I-NP B-VP B-VP B-NP PRP NN VBZ VBG NN O O O O O
Brutus Killed Julius Caesar B-NP B-VP B-NP I-NP NNP VBD NNP NNP B-Per O B-Per I-Per
ludwig experiment \
--dataset nl_data.csv \
  --config_file config.yaml

config.yaml

input_features:
    -
        name: sentence
        type: sequence
        encoder: rnn
        cell: lstm
        bidirectional: true
        reduce_output: null

output_features:
    -
        name: chunks
        type: sequence
        decoder: tagger
    -
        name: part_of_speech
        type: sequence
        decoder: tagger
    -
        name: named_entities
        type: sequence
        decoder: tagger

簡單回歸: 燃油效率預(yù)測

這個例子復(fù)制了 https://www.tensorflow.org/tutorials/Keras/basic_regression 的 Keras 的例子,根據(jù) Auto MPG 數(shù)據(jù)集中的特征來預(yù)測一輛汽車每加侖的行駛里程创泄。

MPG Cylinders Displacement Horsepower Weight Acceleration ModelYear Origin
18.0 8 307.0 130.0 3504.0 12.0 70 1
15.0 8 350.0 165.0 3693.0 11.5 70 1
18.0 8 318.0 150.0 3436.0 11.0 70 1
16.0 8 304.0 150.0 3433.0 12.0 70 1
ludwig experiment \
--dataset auto_mpg.csv \
  --config_file config.yaml

config.yaml

training:
    batch_size: 32
    epochs: 1000
    early_stop: 50
    learning_rate: 0.001
    optimizer:
        type: rmsprop
input_features:
    -
        name: Cylinders
        type: numerical
    -
        name: Displacement
        type: numerical
    -
        name: Horsepower
        type: numerical
    -
        name: Weight
        type: numerical
    -
        name: Acceleration
        type: numerical
    -
        name: ModelYear
        type: numerical
    -
        name: Origin
        type: category
output_features:
    -
        name: MPG
        type: numerical
        optimizer:
            type: mean_squared_error
        num_fc_layers: 2
        fc_size: 64

二分類:欺詐交易識別

transaction_id card_id customer_id customer_zipcode merchant_id merchant_name merchant_category merchant_zipcode merchant_country transaction_amount authorization_response_code atm_network_xid cvv_2_response_xflg fraud_label
469483 9003 1085 23039 893 Wright Group 7917 91323 GB 1962 C C N 0
926515 9009 1001 32218 1011 Mums Kitchen 5813 10001 US 1643 C D M 1
730021 9064 1174 9165 916 Keller 7582 38332 DE 1184 D B M 0
ludwig experiment \
--dataset transactions.csv \
  --config_file config.yaml

config.yaml

input_features:
  -
    name: customer_id
    type: category
  -
    name: card_id
    type: category
  -
    name: merchant_id
    type: category
  -
    name: merchant_category
    type: category
  -
    name: merchant_zipcode
    type: category
  -
    name: transaction_amount
    type: numerical
  -
    name: authorization_response_code
    type: category
  -
    name: atm_network_xid
    type: category
  -
    name: cvv_2_response_xflg
    type: category

combiner:
    type: concat
    num_fc_layers: 1
    fc_size: 48

output_features:
  -
    name: fraud_label
    type: binary
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末艺玲,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子鞠抑,更是在濱河造成了極大的恐慌饭聚,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件搁拙,死亡現(xiàn)場離奇詭異秒梳,居然都是意外死亡,警方通過查閱死者的電腦和手機箕速,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門酪碘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人弧满,你說我怎么就攤上這事婆跑。” “怎么了庭呜?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵滑进,是天一觀的道長。 經(jīng)常有香客問我募谎,道長扶关,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任数冬,我火速辦了婚禮节槐,結(jié)果婚禮上搀庶,老公的妹妹穿的比我還像新娘。我一直安慰自己铜异,他們只是感情好哥倔,可當(dāng)我...
    茶點故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著揍庄,像睡著了一般咆蒿。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上蚂子,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天沃测,我揣著相機與錄音,去河邊找鬼食茎。 笑死蒂破,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的别渔。 我是一名探鬼主播附迷,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼钠糊!你這毒婦竟也來了挟秤?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤抄伍,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后管宵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體截珍,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年箩朴,在試婚紗的時候發(fā)現(xiàn)自己被綠了岗喉。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡炸庞,死狀恐怖钱床,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情埠居,我是刑警寧澤查牌,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站滥壕,受9級特大地震影響纸颜,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜绎橘,卻給世界環(huán)境...
    茶點故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一胁孙、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦涮较、人聲如沸稠鼻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽候齿。三九已至,卻和暖如春苫亦,著一層夾襖步出監(jiān)牢的瞬間毛肋,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工屋剑, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留润匙,地道東北人。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓唉匾,卻偏偏與公主長得像孕讳,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子巍膘,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容