Showing posts with label deep learning. Show all posts
Showing posts with label deep learning. Show all posts

Tuesday, August 23, 2022

Acoustic Feature Extraction with Transformers

The example in Transformers' documentation here shows how to use the wav2vec 2.0 model for automatic speech recognition. However, there are two crucial issues in that example. First, we usually use our data (set) instead of their (available) dataset. Second, we need to extract acoustic features (the last hidden states instead of logits). The following is my example of adapting Transformers to extract acoustic embedding given any audio file (WAVE) using several models. It includes the pooling average from frame-based processing to utterance-based processing for given any audio file. You don't need to perform the pooling average if you want to process your audio file in frame-based processing (remove the `.mean(axis=0)` in the variable `last_hidden_states`).

Basic syntax: wav2vec2 base model

This is the example from the documentation. I replaced the use of the dataset with the defined path of the audio file ('00001.wav').

from transformers import Wav2Vec2Processor, Wav2Vec2Model
import torchaudio
import torch
# load model
processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h")
model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")

# audio file is decoded on the fly
array, fs = torchaudio.load("/data/A-VB/audio/wav/00001.wav")
input = processor(array.squeeze(), sampling_rate=fs, return_tensors="pt")

# apply the model to the input array from wav
with torch.no_grad():
    outputs = model(**input)

# extract last hidden state, compute average, convert to numpy
last_hidden_states = outputs.last_hidden_state.squeeze().mean(axis=0).numpy()

# print shape
print(f"Hidden state shape: {last_hidden_states.shape}")
# Hidden state shape: (768,)


The syntax for the wav2vec2 large and robust model

In this second example, I replace the base model with the large and robust model without finetuning. This example is adapted from here. Note that I replaced 'Wav2Vec2ForCTC' with 'wav2vec2Model'. The former is used when we want to obtain the logits (for speech-to-text transcription) instead of obtaining the hidden states.

from transformers import Wav2Vec2Processor, Wav2Vec2Model
import torch
import torchaudio

# load model
processor = Wav2Vec2Processor.from_pretrained(
    "facebook/wav2vec2-large-robust-ft-swbd-300h")
model = Wav2Vec2Model.from_pretrained(
    "facebook/wav2vec2-large-robust-ft-swbd-300h")

# audio file is decoded on the fly
array, fs = torchaudio.load("/data/A-VB/audio/wav/00001.wav")
input = processor(array.squeeze(), sampling_rate=fs, return_tensors="pt")

with torch.no_grad():
    outputs = model(**input)

last_hidden_states = outputs.last_hidden_state.squeeze().mean(axis=0).numpy()
# printh shape
print(f"Hidden state shape: {last_hidden_states.shape}")
You can replace "facebook/wav2vec2-large-robust-ft-swbd-300h" with "facebook/wav2vec2-large-robust-ft-libri-960h" for the larger fine-tuned model.

 For other models, you may need to change `Wav2Vec2Processor` with `Wav2Vec2FeatureExtractor` for processor variable. In my case, this is needed for the following models:
  • facebook/wav2vec2-large-robust
  • facebook/wav2vec2-large-xlsr-53

The syntax for the custom model (wav2vec-R-emo-vad)

The last one is the example of the custom model. The model is wav2vec 2.0 fine-tuned on the MSP-Podcast dataset for speech emotion recognition. This last example differs from the previous one since the configuration is given by the authors of the model (read the code thoroughly to inspect the details). I replaced the dummy audio file with the real audio file. It is assumed to process in batch (with batch_size=2) by replicating the same audio file.

import torch
import torch.nn as nn
from transformers import Wav2Vec2Processor
from transformers.models.wav2vec2.modeling_wav2vec2 import (
    Wav2Vec2Model,
    Wav2Vec2PreTrainedModel,
)
import torchaudio


class RegressionHead(nn.Module):
    r"""Classification head."""

    def __init__(self, config):

        super().__init__()

        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.dropout = nn.Dropout(config.final_dropout)
        self.out_proj = nn.Linear(config.hidden_size, config.num_labels)

    def forward(self, features, **kwargs):

        x = features
        x = self.dropout(x)
        x = self.dense(x)
        x = torch.tanh(x)
        x = self.dropout(x)
        x = self.out_proj(x)

        return x


class EmotionModel(Wav2Vec2PreTrainedModel):
    r"""Speech emotion classifier."""

    def __init__(self, config):

        super().__init__(config)

        self.config = config
        self.wav2vec2 = Wav2Vec2Model(config)
        self.classifier = RegressionHead(config)
        self.init_weights()

    def forward(
            self,
            input_values,
    ):

        outputs = self.wav2vec2(input_values)
        hidden_states = outputs[0]
        hidden_states = torch.mean(hidden_states, dim=1)
        logits = self.classifier(hidden_states)

        return hidden_states, logits


def process_func(
    wavs,
    sampling_rate: int
    # embeddings: bool = False,
):
    r"""Predict emotions or extract embeddings from raw audio signal."""

    # run through processor to normalize signal
    # always returns a batch, so we just get the first entry
    # then we put it on the device
    # wavs = pad_sequence(wavs, batch_first=True)
    # load model from hub
    device = 'cpu'
    model_name = 'audeering/wav2vec2-large-robust-12-ft-emotion-msp-dim'
    processor = Wav2Vec2Processor.from_pretrained(model_name)
    model = EmotionModel.from_pretrained(model_name)

    y = processor([wav.cpu().numpy() for wav in wavs],          
                   sampling_rate=sampling_rate,
                   return_tensors="pt",
                   padding="longest"
        )
    y = y['input_values']
    y = y.to(device)


    y = model(y)

    return {
        'hidden_states': y[0],
        'logits': y[1],
    }


## test to an audiofile
sampling_rate = 16000
signal = [torchaudio.load('train_001.wav')[0].squeeze().to('cpu') for _ in range(2)]

# extract hidden states
with torch.no_grad():
    hs = process_func(signal, sampling_rate)['hidden_states']
print(f"Hidden states shape={hs.shape}")

Please note for all models, the audio file must be sampled with 16000 Hz, otherwise, you must resample it before extracting acoustic embedding using the methods above. It may not throw an error even if the sampling rate is not 16000 Hz but the results, hence, is not valid since all models were generated based on 16 kHz of sampling rate speech datasets. 

You may also want to extract acoustic features using the opensmile toolkit. The tutorial for Windows users using WSL is available here: http://bagustris.blogspot.com/2021/08/extracting-emobase-feature-using-python.html.

Happy reading. Don't wait for more time to apply these methods to your own audio file.

Friday, June 24, 2022

Membuka dan menyimpan file json

MENYIMPAN file JSON
Studi kasus
Misalkan kita ingin menyimpan dataset berikut (RAVDESS Speech) dalam format json yang berisi file dan labelnya (data speech emotion recognition). Untuk keperluan tersebut kita ingin memisahkan antara data training ('train_meta_data.json') dan data test ('test_meta_data.json'). Skrip berikut memenuhi tujuan tersebut.
import os
import glob
import json

data_dir = '/data/Audio_Speech_Actors_01-24/'
files = glob.glob(os.path.join(data_dir, 'Actor_??', '*.wav'))
files.sort()

data_train = []
data_test = []

for file in files:
    lab = os.path.basename(file).split('-')[2]
    if int(file[-6:-4]) < 20: # speaker 1-19 for training
        data_train.append({
            'path': file,
            'label': lab
        })
    else:                     # speaker 20-24 for test
        data_test.append({
            'path': file,
            'label': lab
        })

with open("train_meta_data.json", 'w') as f:
        json.dump(data_train, f)

with open("test_meta_data.json", 'w') as f:
        json.dump(data_test, f)

MEMBUKA file JSON
import json
filepath = '/data/Audio_Speech_Actors_01-24/train_meta_data.json'
with open(filepath, 'r') as f:
     data_train = json.load(f)

Friday, April 22, 2022

Basic Audio Manipulation With Torchaudio

Recently, I moved my audio processing toolkit from librosa (and others) to Torchaudio. This short writing documented the very basics of torchaudio for audio manipulation: read, resample, and write an audiofile.

Load audio file (read)

The process of loading (reading) an audio file is straightforward, just pass the audio path to `torchaudio.load`. We need to import the needed modules first. Most audio files can be loaded by torchaudio (WAV, OGG, MP3, etc.).
import torchaudio
import torchaudio.transforms as T
wav0, sr0 = torchaudio.load("old_file_48k.wav", normalize=True) 
where wav0 is the output tensor (array) and sr0 is the original sampling rate. Argument `normalize=True` is optional to normalize the waveform. Note that one of my colleagues (a student) found that using `librosa.util.normalize()` resulted in better normalization (peak to peak waveform is -1 to 1) than this torchaudio normalization.
 

Resample

Resample a sampling rate to another sampling rate is done by a Class; the output is a function. Hence, we need to pass the old tensor to the resampler function. Here is an example to convert 48k tensor to 16k tensor.
sr1 = 16000
resampler = T.Resample(sr0, sr1)
wav1 = resampler(wav0)

Save as a new audio file (write)


The process of saving files is also straightforward, just pass the file name, tensor, and sampling rate in order.
torchaudio.save('new_file_16k.wav', wav1, sr1)
Then the new audio file appeared in the current directory. Just set the path and file name if you want to save it in another directory.
 

Reference:

[1] https://pytorch.org/tutorials/beginner/audio_preprocessing_tutorial.html

Wednesday, March 30, 2022

Mencoba Docker

Setelah sekian lama ingin mencoba docker, kali ini saya benar-benar mencobanya. Selama ini saya bisa menghindari docker karena venv dan conda tidak pernah gagal. Karena kali ini conda gagal mendukung GPU di tensorflow 1.15, maka mau tidak mau Docker menjadi solusi terbaik. 

Docker
Gambar 1. Diagram alir ketika venv gagal, berlanjut ke conda, berlanjut ke docker. Selama venv berhasil membuat environment yang diinginkan saya akan memakainya sebagai pilihan pertama, jika tidak baru mencoba conda dan docker, secara bertahap. 

Docker Untuk Menginstall Software (Paket/Library) Baru

Sampai saat ini saya masih memakai Ubuntu 16.04 untuk laptop-laptop pribadi dan Ubuntu 20.04 untuk laptop-laptop kantor. Permasalahan pada OS lama adalah kegagalan untuk menginstall software versi baru. Kasus saya adalah menginstall paket opensmile python versi terbaru (versi 2.4.1) yang membutuhkan library glibc di atas versi 2.31. Library glibc ini tidak bisa diupate. Pernah sekali saya mengupdatenya dan system saya (Centos 7) langsung rusak dan harus install ulang. Docker adalah solusinya.
 
# asumsi docker sudah terinstall
$ docker run -it ubuntu bash
# jika ada masalah permission, lakukan: sudo chmod 666 /var/run/docker.sock
$ apt update
$ apt install python3
$ apt install python3-pip
$ python3 -m pip install opensmile
$ apt install libsndfile1 libsndfile1-dev
$ apt install sox
$ apt insalll ffmpeg
root@6e7dd3cbfee1:/# python3
Python 3.8.10 (default, Mar 15 2022, 12:22:08) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import opensmile
>>> opensmile.__version__
'2.4.1'
>>> exit()
root@6e7dd3cbfee1:/# ldd --version ldd
ldd (Ubuntu GLIBC 2.31-0ubuntu9.7) 2.31
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Roland McGrath and Ulrich Drepper.

Menyimpan file docker dengan commit

Docker tidak didesain untuk menyimpan file, untuk menyimpan file (dan perubahan/update) dari docker yang sedang berjalan dan docker-docker sebelumnya gunakan perintah commit berikut.
Format:
docker commit CONTAINER_ID IMAGE
$ docker ps -a # bisa juga dengan ps -l untuk docker yang sedang berjalan
$ dokcer commit ef7d7090e3c7 ubuntu:opensmile

Docker Untuk Menginstall Software Lama (Tensorflow 1.15 dengan GPU support) 


Skenario: Saya ingin menjalankan kode di repository berikut: Efficient Bigan, dengan GPU RTX 3090, yang saat itu (saat repo itu dibuat dengan tensorflow 1.15) belum diproduksi.
Solusi:
# asumsi docker belum terinstall
$ sudo apt install docker.io
$ curl https://get.docker.com #install curl jika belum ada
$ sudo systemctl --now enable docker
  
$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID) \
      && curl -s -L https://nvidia.github.io/libnvidia-container/gpgkey | sudo apt-key add - \
      && curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
$ sudo apt update
$ docker images      # list images docker 	 	
REPOSITORY                  TAG             IMAGE ID       CREATED       SIZE
nvcr.io/nvidia/tensorflow   22.04-tf1-py3   8b2abbd886f0   2 years ago   9.51GB
$ docker run --gpus all -it --rm nvcr.io/nvidia/tensorflow:22.04-tf1-py3
$ git clone https://github.com/houssamzenati/Efficient-GAN-Anomaly-Detection.git
$ cd Efficient-GAN-Anomaly-Detection
$ python3 main.py gan mnist run --nb_epochs=10 --label=0 
______   _____       _____       ____                                                                                                                   
|_     `.|_   _|     / ___ `.   .'    '.                                                                                                                 
  | | `. \ | |      |_/___) |  |  .--.  |                                                                                                                
  | |  | | | |   _   .'____.'  | |    | |                                                                                                                
 _| |_.' /_| |__/ | / /_____  _|  `--'  |                                                                                                                
|______.'|________| |_______|(_)'.____.'                                                                                                                 
                                                                                                                                                         
                                                                                                                                                         
[09:48:37 INFO @AnomalyDetection] Running script at gan.run_mnist                                                                                        
2022-03-30 09:48:37.916727: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0        
[09:48:37 WARNING @tensorflow] Deprecation warnings have been disabled. Set TF_ENABLE_DEPRECATION_WARNINGS=1 to re-enable them.                          
[09:48:38 WARNING @tensorflow] From /TA/demo/Efficient-GAN-Anomaly-Detection/gan/run_mnist.py:4: The name tf.ConfigProto is deprecated. Please use tf.com
pat.v1.ConfigProto instead.                                                     
...
2022-03-30 09:48:44.229713: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublas.so.11
2022-03-30 09:48:44.683684: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudnn.so.8
[09:48:51 INFO @GAN.train.mnist.fm.0] Epoch terminated
Epoch 0 | time = 7s | loss gen = 0.7218 | loss dis = 1.3530 
[09:48:54 INFO @GAN.train.mnist.fm.0] Epoch terminated
Epoch 1 | time = 3s | loss gen = 0.7747 | loss dis = 1.2383 
[09:48:57 INFO @GAN.train.mnist.fm.0] Epoch terminated
Epoch 2 | time = 3s | loss gen = 0.8793 | loss dis = 1.0877 
[09:49:01 INFO @GAN.train.mnist.fm.0] Epoch terminated
Epoch 3 | time = 3s | loss gen = 1.0170 | loss dis = 0.9235 
[09:49:04 INFO @GAN.train.mnist.fm.0] Epoch terminated
Epoch 4 | time = 3s | loss gen = 1.1724 | loss dis = 0.7746 
[09:49:07 INFO @GAN.train.mnist.fm.0] Epoch terminated
Epoch 5 | time = 3s | loss gen = 1.3378 | loss dis = 0.6493 
[09:49:11 INFO @GAN.train.mnist.fm.0] Epoch terminated
Epoch 6 | time = 3s | loss gen = 1.5056 | loss dis = 0.5522 
[09:49:14 INFO @GAN.train.mnist.fm.0] Epoch terminated
Epoch 7 | time = 3s | loss gen = 1.6597 | loss dis = 0.4744 
[09:49:17 INFO @GAN.train.mnist.fm.0] Epoch terminated
Epoch 8 | time = 3s | loss gen = 1.7992 | loss dis = 0.4116 
[09:49:21 INFO @GAN.train.mnist.fm.0] Epoch terminated
Epoch 9 | time = 3s | loss gen = 1.8616 | loss dis = 0.3848 
[09:49:21 WARNING @GAN.train.mnist.fm.0] Testing evaluation...
[09:54:19 INFO @GAN.train.mnist.fm.0] Testing : mean inference time is 1.5292
Testing | PRC AUC = 0.7183

Me-mount direktori 

Alih-alih membuat commit setiap kali kita mengedit, kita bisa memount direktori saat memanggil docker.
Skenario: Mengedit file diluar docker, mengeksekusi file (misal python) didalam docker. Caranya adalah sebagai berikut.
$ docker run --gpus all -it --mount type=bind,source=/TA,target=/TA tf1.15:py3
Dimana `source` adalah sumber direktori, dan `target` adalah target direktori. Image docker sebelumnya sudah saya commit menjadi `tf1.15` dengan tag `py3`. 

Menambahkan docker ke sudoers

Ketika membuka docker, terlihat bahwa tanda di baris kiri terminal adalah sharp #, ini menandakan kita masuk sebagai super user (sudo). Karenanya ada error saat membuka docker pertama kali (harus chmod 666 dulu). Solusi ini hanya berjalan sementara, untuk solusi permanen kita bisa menambahkan docker ke grup sudoers sebagai berikut.
# menambahkan grup baru bernama docker
$ sudo groupadd docker
# menambahkan $USER ke grup docker
$ sudo usermod -aG docker $USER
# merefresh grup
$ newgrp docker
Demikian tutorial singkat docker ini, semoga bermanfaat.

Referensi;
[1] https://docs.docker.com/engine/install/linux-postinstall/

Thursday, January 27, 2022

Ekstraksi Fitur Akustik dengan Torchaudio

Kode di bawah ini mengekstrak tiga fitur akustik -- spectrogram, melspectrogram, dan mfcc -- dari sebuah file audio "filename" (wav, mp3, ogg, flacc, dll). Ketiga fitur akustik tersebut merupakan fitur-fitur akustik terpenting dalam pemrosesan sinyal wicara. Keterangan singkat ada di dalam badan kode. Hasil plot ada di bawah kode.

###
#import torch
import torchaudio
from matplotlib import pyplot as plt
import librosa

# show torchaudio version
# torch.__version__
print(torchaudio.__version__)


def plot_spectrogram(spec, title=None, ylabel="freq_bin", aspect="auto",
                     xmax=None):
    fig, axs = plt.subplots(1, 1)
    axs.set_title(title or "Spectrogram (db)")
    axs.set_ylabel(ylabel)
    axs.set_xlabel("frame")
    im = axs.imshow(librosa.power_to_db(spec), origin="lower", aspect=aspect)
    if xmax:
        axs.set_xlim((0, xmax))
    fig.colorbar(im, ax=axs)
    plt.show(block=False)


filename = "/home/bagus/train_001.wav"  # change with your file
waveform, sample_rate = torchaudio.load(filename)

# Konfigurasi untuk spectrogam, melspectrogram, dan MFCC
n_fft = 1024
win_length = None  # jika None maka sama dengan n_fft
hop_length = 512   # y-axis in spec plot
n_mels = 64  # y-axis in melspec plot
fmin = 50
fmax = 8000
n_mfcc = 40  # must be smaller than n_mels, will be y-axis in plot

# definisi kelas untuk ekstraksi spektrogram
spectrogram = torchaudio.transforms.Spectrogram(
    n_fft=n_fft,
    win_length=win_length,
    hop_length=hop_length,
    center=True,
    pad_mode="reflect",
    power=2.0,
)

# Show plot of spectrogram
spec = spectrogram(waveform)
print(spec.shape)  # torch.Size([1, 513, 426])
plot_spectrogram(spec[0], title=f"Spectrogram - {str(filename)}")


## kelas untuk ekstraksi melspectrogram
melspectogtram = torchaudio.transforms.MelSpectrogram(
    sample_rate=sample_rate,
    n_fft=n_fft,
    win_length=win_length,
    hop_length=hop_length,
    n_mels=n_mels,
    f_min=fmin,
    f_max=fmax,
)

# Calculate melspec
melspec = melspectogtram(waveform)
melspec.shape # torch.Size([1, 513, 426])
plot_spectrogram(melspec[0], title=f"Melspectrogam - {str(filename)}")

## kelas untuk ekstraksi MFCC
mfcc_transform = torchaudio.transforms.MFCC(
    sample_rate=sample_rate,
    n_mfcc=n_mfcc,
    melkwargs={
      'n_fft': n_fft,
      'n_mels': n_mels,
      'hop_length': hop_length,
      'mel_scale': 'htk',
    }
)

# plot mfcc
mfcc = mfcc_transform(waveform)
print(mfcc.shape) # torch.Size([1, 40, 426])
plot_spectrogram(mfcc[0], title=f"MFCC - {str(filename)}")
###

Plot 


Monday, April 26, 2021

Running IPython in multiple GPUs

Here is a simple configuration to run IPython on different GPUs on a single PC.

1. Check available GPU in PC via terminal, "$ sudo lshw -C display"

Checking number of GPUs

2. Launch "$ CUDA_AVAILABLE_DEVICES=0 ipython3" to use IPython using first GPU

Set IPython to use the first GPU (on OS level)

3. Launch "$ CUDA_AVAILABLE_DEVICES=1 ipython" to use IPython using second GPU

Set IPython to use the second GPU

4. Check "$ nvidia-smi" to confirm both GPUs are running simultaneously

Output of nvidia-smi when two GPUs are used simultaneously

5. For comparison, here is the output of 2 GPUs used in IPython without commands above

IPython without configuration resulting two GPUs output

Ouput of nvidia-smi without configuration

It can be seen from both IPython outputs and nvidia-smi that the configuration works. Each IPython window outputted a single GPU, while without configuration (without adding "CUDA_VISIBLE_DEVICES=X") the output of IPython is two GPUs. Also, the nvidia-smi output shows two GPUs work simultaneously with the given configs, while without config it shows only one GPU is running (the consumed memory of the second GPU only 416MiB meaning idle condition).

 

Update  2021/05/13

I checked again today, the above-mentioned steps sometimes still failed to choose GPU on multiple GPUs. The following workaround works for me.

Choose GPU 0

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0"

# check with
import tensorflow as tf
tf.test.is_gpu_available()
The same steps apply to GPU 1. These steps also can be applied using the shell command "export".
export CUDA_DEVICE_ORDER="PCI_BUS_ID"
export CUDA_VISIBLE_DEVICES="1" 
Please be sure not to make typo (E.g, VISIBLE -> VISBLE), otherwise, the configuration won't work. There is no error message when we make string typos in a shell.

Monday, December 21, 2020

Jetson AGX change mode

Some important commands to change the mode of Jetson AGX.

Change CPU and Power mode
sudo nvpmodel -m 0 # change power mode to 1 

Change Fan mode
sudo nvpmodel -d quiet # to change to quiet mode
sudo nvpmodel -d cool # to change to cool mode

Change Clocks mode

Check current clock mode
sudo /usr/bin/jetson_clocks --show

Change clock to max mode
sudo /usr/bin/jetson_clocks 


Reference:
  1. https://docs.nvidia.com/jetson/l4t/index.html#page/Tegra%20Linux%20Driver%20Package%20Development%20Guide/power_management_jetson_xavier.html

Thursday, July 09, 2020

How-to: Install Numba and LibROSA in Jetson AGX Xavier (Ubuntu 18.04)

Installing Numba and Librosa in Jetson AGX Xavier is very painful. To document my experience, I wrote this note. Here is how-to install Numba and Librosa on AGX Xavier.

Device: AGX Xavier Dev Kit (32GB RAM)
Software
OS: Ubuntu 18.04
nvidia-jetpack: Version: 4.4-b186
python: Version 3.6.9
llvm: Version 9.0.1 (and 7.1.0)

First, we need to install llvmlite. We can install either from source or via apt. I installed it from the source as shown below.

cd /tmp
wget https://github.com/llvm/llvm-project/releases/download/llvmorg-9.0.1/llvm-9.0.1.src.tar.xz
tar -xvf llvm-9.0.1.src.tar.xz 
cd llvm-9.0.1.src/
mkdir llvm_build_dir
cd llvm_build_dir
cmake ../ -DCMAKE_BUILD_TYPE=Release -DLLVM_TARGETS_TO_BUILD="ARM;X86;AArch64"
make -j4
sudo make install
cd bin/
echo "export LLVM_CONFIG=\""`pwd`"/llvm-config\"" >> ~/.bashrc
echo "alias llvm='"`pwd`"/llvm-lit'" >> ~/.bashrc
source ~/.bashrc
python3.6 -m pip install --user -U llvmlite==0.31

If you want to install via apt, do it as follows. I use llvm-7 from Ubuntu repository (llvm-9 fails installing llvmlite 0.31 but success for 0.33).

sudo apt install llvm-7

If you install llvm via apt, you need to specify where llvm-config is located in .bashrc. For example here is mine. First, locate llvm-config.
s1820002@s1820002-desktop:~$ locate llvm-config
/usr/bin/llvm-config-7
/usr/include/llvm-7/llvm/Config/llvm-config.h
/usr/lib/llvm-7/bin/llvm-config

Then add the location of llvm-config to .bashrc.
export LLVM_CONFIG=/usr/lib/llvm-7/bin/llvm-config

Please be remembered that you need to `source .bashrc` after you edit your .bashrc.

As an alternative to using .bashrc, you can make softlink by mapping llvm-config-9 to llvm-config.
$ cd /usr/bin
$ sudo ln llvm-config-9 llvm-config

The installation of llvm must success before installing llvmlite. If installation of llvmlite by the last line on the script above success, it shows like this one,

Collecting llvmlite
Installing collected packages: llvmlite
Successfully installed llvmlite-0.33.0

If you face an error regarding `setuptools`, you may upgrade your setuptools as follows.

python3.6 -m pip install --user -U setuptools

Now, we can install numba. We need numba version 0.48 to install librosa 0.7.2. To install Numba, first, we must disable tbb.h according to this.

sudo mv /usr/include/tbb/tbb.h /usr/include/tbb/tbb.h.bak

Then, install numba as the following:
bagus@s1820002:~$ python3.6 -m pip install --user -U numba==0.48
Collecting numba==0.48
Collecting setuptools (from numba==0.48) Using cached
 https://files.pythonhosted.org/packages/41/fa/60888a1d591db07bc9c17dce2bcfb9f00ac507c0a23ecb827e76feb8f816/setuptools-49.1.0-py3-none-any.whl
Collecting numpy>=1.15 (from numba==0.48)
Collecting llvmlite<0 .32.0="">=0.31.0dev0 (from numba==0.48)
Installing collected packages: setuptools, numpy, llvmlite, numba
Successfully installed llvmlite-0.33.0 numba-0.50.1 numpy-1.19.0 setuptools-49.1.0

Again, it must install numba without fail to be able to install Librosa.
Before installing librosa, the following packages must be installed via apt.
sudo apt-get install libblas-dev liblapack-dev libatlas-base-dev gfortran

Finally, we can install librosa via pip as below.
bagus@s1820002:~$ python3.6 -m pip install --user -U librosa
Collecting librosa
Collecting resampy>=0.2.2 (from librosa)
Collecting numpy>=1.15.0 (from librosa)
Collecting numba>=0.43.0 (from librosa)
Collecting scikit-learn!=0.19.0,>=0.14.0 (from librosa)
Collecting joblib>=0.12 (from librosa) Using cached
 https://files.pythonhosted.org/packages/51/dd/0e015051b4a27ec5a58b02ab774059f3289a94b0906f880a3f9507e74f38/joblib-0.16.0-py3-none-any.whl
Collecting scipy>=1.0.0 (from librosa)
Collecting soundfile>=0.9.0 (from librosa) Using cached
 https://files.pythonhosted.org/packages/eb/f2/3cbbbf3b96fb9fa91582c438b574cff3f45b29c772f94c400e2c99ef5db9/SoundFile-0.10.3.post1-py2.py3-none-any.whl
Collecting decorator>=3.0.0 (from librosa) Using cached
 https://files.pythonhosted.org/packages/ed/1b/72a1821152d07cf1d8b6fce298aeb06a7eb90f4d6d41acec9861e7cc6df0/decorator-4.4.2-py2.py3-none-any.whl
Collecting six>=1.3 (from librosa) Using cached
 https://files.pythonhosted.org/packages/ee/ff/48bde5c0f013094d729fe4b0316ba2a24774b3ff1c52d924a8a4cb04078a/six-1.15.0-py2.py3-none-any.whl
Collecting audioread>=2.0.0 (from librosa)
Collecting llvmlite<0 .34="">=0.33.0.dev0 (from numba>=0.43.0->librosa)
Collecting setuptools (from numba>=0.43.0->librosa) Using cached
 https://files.pythonhosted.org/packages/41/fa/60888a1d591db07bc9c17dce2bcfb9f00ac507c0a23ecb827e76feb8f816/setuptools-49.1.0-py3-none-any.whl
Collecting threadpoolctl>=2.0.0 (from scikit-learn!=0.19.0,>=0.14.0->librosa) Using cached
 https://files.pythonhosted.org/packages/f7/12/ec3f2e203afa394a149911729357aa48affc59c20e2c1c8297a60f33f133/threadpoolctl-2.1.0-py3-none-any.whl
Collecting cffi>=1.0 (from soundfile>=0.9.0->librosa)
Collecting pycparser (from cffi>=1.0->soundfile>=0.9.0->librosa) Using cached
 https://files.pythonhosted.org/packages/ae/e7/d9c3a176ca4b02024debf82342dab36efadfc5776f9c8db077e8f6e71821/pycparser-2.20-py2.py3-none-any.whl
Installing collected packages: six, numpy, scipy, llvmlite, setuptools, numba, resampy, threadpoolctl, joblib, scikit-learn, pycparser, cffi, soundfile, decorator, audioread, librosa
Successfully installed audioread-2.1.8 cffi-1.14.0 decorator-4.4.2 joblib-0.16.0 librosa-0.7.2 llvmlite-0.33.0 numba-0.50.1 numpy-1.19.0 pycparser-2.20 resampy-0.2.2 scikit-learn-0.23.1 scipy-1.5.1 setuptools-49.1.0 six-1.15.0 soundfile-0.10.3.post1 threadpoolctl-2.1.0

Now everything seems good. We can do audio processing in Jetson AGX. Librosa is the best audio library in python so far. Having it installed on Jetson is a basic requirement.

BONUS: Installing TensorFlow
Step-by-step:
1. Install the following packages.
sudo apt-get install libhdf5-serial-dev hdf5-tools libhdf5-dev zlib1g-dev zip libjpeg8-dev
2. Install/upgrade testresources
python3.6 -m pip install --user -U testresources
3. Installing other python dependencies
python3.6 -m pip future==0.17.1 mock==3.0.5 h5py==2.9.0 keras_preprocessing==1.0.5 keras_applications==1.0.8 gast==0.2.2 futures protobuf pybind11
4. Install tensorflow.
python3.6 -m pip install --user --pre --extra-index-url https://developer.download.nvidia.com/compute/redist/jp/v43 'tensorflow<2' 
output:
Successfully installed absl-py-0.9.0 astor-0.8.1 google-pasta-0.2.0 grpcio-1.30.0 importlib-metadata-1.7.0 markdown-3.2.2 opt-einsum-3.2.1 tensorboard-1.15.0 tensorflow-1.15.2+nv20.3.tf1 tensorflow-estimator-1.15.1 termcolor-1.1.0 werkzeug-1.0.1 wrapt-1.12.1 zipp-3.1.0
5. Test the GPU device.
import tensorflow as tf
tf.test.gpu_device_name()
output:
>>> tf.test.gpu_device_name()
2020-07-10 16:01:36.242822: W tensorflow/core/platform/profile_utils/cpu_utils.cc:98] Failed to find bogomips in /proc/cpuinfo; cannot determine CPU frequency
2020-07-10 16:01:36.244367: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x37b6c3f0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-07-10 16:01:36.244536: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
2020-07-10 16:01:36.259171: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1
2020-07-10 16:01:36.432077: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:950] ARM64 does not support NUMA - returning NUMA node zero
2020-07-10 16:01:36.432674: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x37a81480 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
2020-07-10 16:01:36.432768: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Xavier, Compute Capability 7.2
2020-07-10 16:01:36.433580: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:950] ARM64 does not support NUMA - returning NUMA node zero
2020-07-10 16:01:36.433892: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: 
name: Xavier major: 7 minor: 2 memoryClockRate(GHz): 1.377
pciBusID: 0000:00:00.0
2020-07-10 16:01:36.433987: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.0
2020-07-10 16:01:36.467839: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10.0
2020-07-10 16:01:36.496813: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10.0
2020-07-10 16:01:36.534413: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10.0
2020-07-10 16:01:36.576197: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10.0
2020-07-10 16:01:36.600464: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10.0
2020-07-10 16:01:36.688185: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7
2020-07-10 16:01:36.688573: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:950] ARM64 does not support NUMA - returning NUMA node zero
2020-07-10 16:01:36.690082: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:950] ARM64 does not support NUMA - returning NUMA node zero
2020-07-10 16:01:36.690253: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0
2020-07-10 16:01:36.690456: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.0
2020-07-10 16:01:38.484495: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-07-10 16:01:38.484668: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186]      0 
2020-07-10 16:01:38.484715: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0:   N 
2020-07-10 16:01:38.485215: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:950] ARM64 does not support NUMA - returning NUMA node zero
2020-07-10 16:01:38.485695: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:950] ARM64 does not support NUMA - returning NUMA node zero
2020-07-10 16:01:38.485953: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/device:GPU:0 with 23699 MB memory) -> physical GPU (device: 0, name: Xavier, pci bus id: 0000:00:00.0, compute capability: 7.2)
'/device:GPU:0
Source:
[1] https://github.com/jefflgaol/Install-Packages-Jetson-ARM-Family
[2] https://forums.developer.nvidia.com/t/install-python-packages-librosa-jetson-tx2-developer-kit-problem/126337/5
[3] https://learninone209186366.wordpress.com/2019/07/24/how-to-install-the-librosa-library-in-jetson-nano-or-aarch64-module/

Wednesday, March 25, 2020

Apa bedanya training, validasi, development dan test set ?

Dalam sebuah seminar/konferensi ilmiah, saya bertanya kepada pemateri: Kenapa data yang dipakai untuk validasi dan test sama? Menurut beliau, istilah validasi dan test dalam machine learning sama. Menurut saya ini salah. Data validasi tidak boleh dipakai untuk test (karena tentu saja, hasilnya akan lebih bagus). Data validasi sama dengan data development, keduanya, validation dan development, merupakan istilah yang sama untuk "tuning model" dari hasil training.

Partisi data Training, Validasi, dan Test (sumber gambar: disini)

Merujuk pada StackOverflow:

Thursday, June 20, 2019

Tentang layer TimeDistributed pada Keras...

TimeDistributed merupakan salah satu (wrapper) layer pada keras yang berfungsi untuk membagi weight pada slice temporal pada data 3D. Susah difahami? Perhatikan contoh berikut.

Saya punya data X. Ukurannya (32, 10, 16), seperti contoh pada dokumentasi Keras.

x = np.random.random(size=(32, 10, 16)

Artinya, saya punya 32 data (sample). Setiap sample berisi data (10, 16): 10 baris dan 16 kolom. Ketika saya mengaplikasikan suatu layer (katakanlah, dan paling umum: Dense), agar bobot dari satu layer tersebut merata pada setiap elemen maka perlu kita gunakan timedistributed layer ini.

Perhatikan contoh berikut,
model0 = Sequential()
model0.add(Dense(8, input_shape=(10, 16)))
model0.summary()
Hasilnya adalah sebagai berikut,
---
Model: "sequential_6"
_________________________________________________________________
Layer (type)    Output Shape    Param # 
=================================================================
time_distributed_1 (TimeDist (None, 10, 8)    136 
=================================================================
Total params: 136
Trainable params: 136
Non-trainable params: 0
Bedakan dengan ini,
model1 = Sequential()
model1.add(Dense(8, input_shape=(10, 16)))
model1.summary()
Hasilnya,
---
Model: "sequential_5"
_________________________________________________________________
Layer (type)  Shape  Param # 
=================================================================
dense_3 (Dense)    (None, 10, 8)    136 
=================================================================
Total params: 136
Trainable params: 136
Apa perbedaannya? Tidak ada. Saya juga bingung. Mari kita cari contoh lain, dari machinelearningmastery.
Sebenarnya, jika kita teliti, ada perbedaan bentuk output shape dari kedua contoh diatas, yang pertama memberikan bentuk ouput (TimeDist(None, 8, 10)), sedangkan yang kedua hanya (None, 8, 10).

Wednesday, June 19, 2019

Implementasi Pengenalan Emosi dari Sinyal Wicara Berbasis Deep Learning dengan Keras

Tulisan ini agak panjang, membahas implementasi pengenalan emosi dari sinyal wicara dengan teknik deep learning. Perkakas yang akan kita pakai adalah Keras. Kode python yang dipakai sebenarnya bukan dari saya, namun saya modifikasi dari [1] dan [2]. Baiklah, mari kita mulai.

Ide

Ide dasar penelitian di bidang speech emotion recognition (pengenalan emosi dari sinyal wicara) adalah bahwa sinyal wicara mengandung informasi emosi dari pembicara. Contoh sederhana, suara orang marah akan sangat berbeda dengan suara orang sedih dan senang. Dengan mengenali (pola) suara orang marah, senang, sedih, dll, kita akan bisa mengenali emosi seseorang dari suaranya.  Berikut ilustrasi pengenalan emosi dari penelepon.
Pengenalan emosi penelepon secara otomatis oleh Artificial Intelligence (AI)
Sumber:https://medium.com/@alitech_2017/voice-based-emotion-recognition-framework-for-films-and-tv-programs-2a6abbb77242


Diagram Alir Sistem

Secara umum, sistem pengenalan emosi dari sinyal wicara terdiri dari dua blok utama (selain input dan output):
  1. Ekstraksi Fitur
  2. Klasifikasi
Kode yang kita buat pun juga disimpan dalam dua blok tersebut: save_feature.py dan ser_ravdess.py. Input system adalah speech dataset, dalam hal ini kita pakai dataset RAVDESS [3]. Output yang kita ingin kita capai adalah kategori emosi secara diskrit (01 = neutral, 02 = calm, 03 = happy, 04 = sad, 05 = angry, 06 = fearful, 07 = disgust, 08 = surprised).

Diagram blok pengenalan emosi dari sinyal wicara

Dataset

Friday, May 31, 2019

Keras untuk permasalahan regresi

Pada posting sebelumnya telah didemokan penggunaan Keras sebagai solusi permasalahan klasifikasi. Pada banyak kasus nyata, permasalahan yang dihadapi adalah regresi bukan klasifikasi. Misal, pada prediksi cuaca, prediksi jumlah pengunjung, prediksi temperature, dll, dimana output dari model adalah nilai numerik, bukan kategori diskrit. Deep learning didesain untuk dapat menangani baik permasalahan klasifikasi maupun regresi (juga clustering). Pada posting ini akan didemokan bagaimana Deep Learning bisa menyelesaikan permasalah regresi sederhana.


Problem

Permasalahan yang kita angkat sebagai contoh adalah fungsi matematik sederhana berikut,

$$ f(x) = 2x + 3 $$

Dimana $x$ merupakan input dan $f(x)$ merupakan nilai output. Misal, kita ingin membuat model yang bisa memberikan prediksi nilai $f(x)$ diberikan nilai input $x$ dimana sebelumnya model kita latih dengan range nilai $x$ yang diberikan. Model deep learning ini akan kita implementasikan dengan Keras.

Implementasi
Implementasi deep learning ini akan mengikuti pola yang saya tulis disini: https://bagustris.blogspot.com/2019/04/implementasi-deep-learning-dengan-keras.html

Input-Output data

Input-output data, sesuai persamaan di atas, didefinisikan dalam python numpy sebagai berikut.
import numpy as np
x_train = np.arange(0, 10.01, 0.01)
y_train = 2*x_train + 3             #**2 + 3


Model

Untuk membuat model, kita buat fungsi `build_model`. Model yang kita bangun terdiri dari tiga layer: 2 dense (fully connected) layer dan satu output layer. Input layer akan masuk pada dense layer pertama. Model tersebut bisa kita gambarkan sebagai berikut.

Berikut fungsi `build_model` untuk membangun model seperti gambar di atas.

Friday, April 26, 2019

Menggunakan GridSearchCV untuk optimasi hyperparameter pada Keras

Salah satu permasalahan pada pembangunan (development) model deep learning adalah mencari hyperparameter optimal. Contohnya sebagai berikut:
  1. Berapa ukuran batch_size optimal: 16, 32, 64 atau 128?
  2. Berapa epoch optimal untuk menjalankan model deep learning: 10, 20, 50 atau 100?
  3. Apa optimizer terbaik untuk deep learning model ini: atam, rmsprop, atau adadelta...?
Dan masih banyak hiperparameter lainnya yang bisa dioptimasi: Dropout, jumlah node, jumlah layer, fungsi aktivasi apa yang digunakan, dan lain-lainnya. Habis waktu kita jika digunakan untuk trial-error mencoba mengganti satu-satu parameter tersebut untuk mencari model terbaik. Salah satu solusi dari permasalahan ini adalah dengan menggunakanGridSearch.

Monday, April 08, 2019

Implementasi Deep Learning dengan Keras: Terminologi dasar

Berikut konsep deep learning dengan Keras dalam 30 detik (6 detik per baris membaca):
model = Sequential()
model.add(Dense(XX, input_dim=Y)
model.add(Dense(Z))
model.compile(loss='nama_loss_function', optimizer='nama_optimizer', metrics=['nama_metrik'])
model.fit(training_input, training_ouput, epochs=AA)

Terminologi penting (tak kenal maka tak paham?!):

Model: Tipe model yang digunakan. Ada dua: sekuensial dan functional API.
Contoh:
model = Sequential()

Dense: Menambahkan unit atau node beserta argumennya, dari satu layer ke layer selanjutnya. Dengan kata lain, "fully-connected layer", atau "feed forward network", atau "multi-layer perceptron".


Contoh:

model.add(Dense(32, input_dim=2)
Kode di atas membuat layer dengan jumlah 32 unit dan 16 unit input. Jumlah learnable parameternya adalah 16*32+32 = 544. Check dengan model.summary(). Jika kita tambahkan lagi,
model.add(32) 
Maka sekarang kita mempunyai dua layer yang masing-masing berisi 32 unit. Total learnabale parameternya adalah 544+ (32*32+32) = 1600. Check dengan kode yang telah diberikan di atas.

Compile: Mengkonfigurasi model untuk melatih data yang diberikan
Contoh:
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
Fit: Mencari hubungan input dan output data, dengan kata lain: membangun/melatih model.
Contoh:
model.fit(train_input, train_output, batch_size=16, epochs=500)

Empat terminologi di atas merupakan step dasar untuk melakukan training data dengan deep learning. Namun masing-masing terminologi memiliki argumen. Agar lengkap, berikut penjelasan singkat argumen-argmunen tersebut.

Friday, March 29, 2019

Word Embedding dan Implementasinya dalam Python (Keras)

Tulisan ini merupakan implementasi dari tulisan sebelumnya, "Vektor dari Kata dan GloVe Embedding". Word embedding merupakan representasi dari kata. Dua teknik yang paling umum dipakai dalam word embedding telah dipaparkan sebelumnya: vektor kata dan GloVe embedding. Tulisan ini adalah implementasi dari teknik tersebut dengan menggunakan bahasa pemrograman Python dan modul Keras.

Misalkan kita punya kumpulan lima kata-kata baik dan enam kata-kata jelek seperti dibawah. Kata-kata baik kita labelkan dengan angka "1" sedangkan kata-kata jelek kita labelkan dengan angka "0".

import numpy as np
kata = ["Bagus!", "Ampuh!", "cantik!", "Mantap!", "Cakep!", 
        "Jelek", "Rusak", "Nol", "Omong kosong", "Busuk", "Tidak"]
label = np.array ([1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0])

Kemudian kata-kata di atas kita rubah menjadi integer
# merubah kata menjadi integer
from keras.preprocessing.text import one_hot
vocab_size = 50
encoded_docs = [one_hot(d, vocab_size) for d in kata]
print(encoded_docs)

Karena panjang maksimal dari elemen kata adalah dua buah (yakni kata "Omong kosong"), kita jadikan kata-kata lainnya memiliki panjang dua buah kata.

Thursday, March 28, 2019

Data yang besar mengalahkan algoritma yang baik

Dalam sebuah workshop yang saya ikuti setahun dua tahun yang lalu di Trieste, seorang pemateri dengan pedenya menyampaikan: "bigger data win over good algorithm", data yang besar mengalahkan algortima yang baik. Saya tercengang. Benarkah...? Selama sekolah, S1~S2, saya diajari dan dituntut untuk menghasilkan algoritma yang baik dari data pengukuran fisis untuk aplikasi kontrol, prediksi, diagnosa dan lain sebagainya. Namun sekarang paradigmanya berubah, bukan bagaimana meng-improve algoritma, tapi mempebesar jumlah data. Tidak sepenuhnya benar memang, namun ini jauh lebih mudah. Akan lebih mudah mengakuisisi lebih banyak data daripada mengimprove/memodifikasi algoritma yang biasanya membutuhkan matematika yang cukup rumit.

Benar adanya, tak semata-mata algoritma/metode yang baik, tapi juga data yang banyak. Gampangannya, orang yang yamg "pintar" tapi jarang belajar dibanding dengan orang yang "rajin" belajar dari banyak data. Pengalaman menunjukkan, tipe orang disebut terakhir lebih banyak berhasilnya daripada tipe orang yang disebut pertama.

Analogi lagi, data vs algoritma: mana yang lebih penting adalah seperti membandingkan mana yang lebih dulu: telur atau ayam. Awalnya saya, mungkin seperti kebanyakan orang juga, berpikiran telur lebih dahulu. Alasannya: telur lebih rigid, lebih statis, dan lebih kecil daripada ayam. Namun hasil penelitian membuktikan bahwa ayam lebih dahulu daripada telur (artinya Tuhan menciptakan ayam dulu, ini lebih masuk akal). Begitu juga dengan data vs algoritma: data-lah akhirnya yang menang, tentunya data yang banyak, big atau bahkan very big.

Jadi tunggu apa lagi? Cari data sebanyak-banyaknya, seakurat mungkin! Mengumpulkan data tidak sesulit membangun algortima. Kalau membangun algortima, kita butuh mikir exktra, menurunkan rumus matematik, dan mengimplementasikannya dalam bahasa pemrograman. Sedangkan untuk mengumpulkan data, kita cuma butuh waktu, keuletan, dan ketekunan. Contohnya untuk data teks, kita perlu sabar dan rajin mengumpulkan kalimat, tokenisasi, mengetik dan sebagaiknya. Untuk data suara, kita perlu merekam, mengedit dan memanipulasi (tambahkan noise, hilangkana noise, dsb). Jauh lebih mudah untuk memperbanyak data daripada memperbaiki algoritma.

Garbage In Garbage Out
Salah satu prinsip yang penting dalam machine learning dan pengenalan pola adalah "data yang baik", berkualitas. Jika data yang kita masukkan adalah sampah, maka hasilnya juga sampah. Maka, selain memperbanyak data, yang harus kita perhatikan adalah kualitas data tersebut. Jangan sampai data yang kita latih, misal dengan deep learning, merupakan data sampah, sehingga hasilnya juga sampah. Disinilah pentingnya preprocessing.

Berapa data yang "besar" itu?

Pertanyaanya selanjutnya, jika data yang besar mengalahkan algoritma yang baik, seberapa besar data yang besar itu? Ian Goodfellow et al. dalam bukunya "Deep learning" berargumen sebagai berikut,
As of 2016, a rough rule of thumb is that a supervised deep learning algorithm will generally achieve acceptable performance with around 5,000 labeled examples per category, and will match or exceed human performance when trained with a dataset containing at least 10 million labeled examples. Working successfully with datasets smaller than this is an important research area, focusing in particular on how we can take advantage of large quantities of unlabeled examples, with unsupervised or semi-supervised learning.
 Jadi, 5000 data yang terlabeli dengan benar merupakan data minimal dari sisi best practice. Tenju saja, semakin besar semakin baik.

Referensi:
  1. Alon Halevy, P. Norvig, F. Pereira, "The Unreasonable Effectiveness of Data". Available online:https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/35179.pdf
  2. https://www.datasciencecentral.com/profiles/blogs/data-or-algorithms-which-is-more-important

Friday, March 15, 2019

Atensi, hubungannya dengan cocktail party problem dan deep learning

Beberapa hari ini saya kembali membaca beberapa paper tentang fenomena "cocktail party", tema penelitian saya saat S1 dan S2. Dulu, bahkan sampai minggu lalu, saya hanya membaca banyak paper dari aspek statitsik, algoritma, dan aplikasinya. Padahal teknik tersebut (ICA/BSS) diusulkan untuk meniru cara kerja otak manusia. Karena sedang mengambil kuliah tentang "perceptual", sekarang saya sedang membaca beberapa paper tentang bagaimana otak memproses fenomea "cocktail party". Kali ini, semua yang saya baca adalah tentang persepsi, kognisi dan proses biologi, bukan rekayasa matematika atau deep learning, tapi tentang jaringan saraf sebenarnya.

Atensi

Apakah atensi itu? Atensi merupakan proses kognitif dan perilaku untuk memilih informasi tertentu dan mengabaikan informasi lainnya. Studi tentang atensi ini mulai berkembang ketika Cherry pada tahun 1953 mempublikasikan papernya tentang eksperimen "shadowing task": dimana responden diperdengarkan dua pesan melalui headphone secara dichotic (satu pesan untuk tiap kanal, kanan dan kiri). Pesan terserbut merupakan pesan utama (attended) dan sampingan (non-attended). Cherry menemukan bahwa sangat kecil sekali reponden memperhatikan pesan sampingan, misalnya apakah pesan itu diucapkan oleh laki-laki/wanita, bahasa apa yang digunakan, dll. Eksperimen Cherry ini membuka jalan lahirnya teori tentang atensi dan beberapa modelnya.

Gambar 1. Model atensi Broadbent dan Treisman

Thursday, August 02, 2018

Deep Learning: CNN

Tulisan ini adalah kelanjutan dari tulisan sebelumnya tentang Jaringan Syaraf Tiruan (JST) .

Deep learning (tidak hanya) terbagi menjadi dua cabang algoritma besar: CNN (Convolutional NN) dan RNN (Recurrent NN). Masih banyak metode lainnya, namun seolah tenggelam oleh dua algoritma tersebut. Perbedaan utama CNN dan RNN adalah sebagai berikut.

CNN:
  1. Input berupa tensor dengan ukuran tetap (e.g: image)
  2. Output juga berupa vector dengan ukuran tetap (e.g. probablitias dari beberapa kelas berbeda)
RNN:
  1. Beroperasi pada sekuen vector atau tensor
  2. Contoh aplikasi: Text translation, speech to text, speech recognition, text to speech.

Sederhanya, jika input bisa diubah dalam bentuk "image", kita pakai CNN, jika data berupa vektor kita pakai RNN. Contoh, data ujaran (speech) juga bisa ditraining dengan metode CNN dengan memberi input jaringan berupa "image" spectrogram.

Kembali ke CNN. Masalah terbesar JST/NN. 

Jika sebuah image berukuran 50 x 50 pixel sebagai input, dan JST memiliki konfigurasi 2 hidden layer dengan layer pertama berisi 7500 neuron (node) dan layer kedua berisi 2000 node dan 2 ouput, maka jumlah weight (bobot) pada arsitektur JST tersebut:
$$ (7500 \times 2000) + (2000 \times 2) = 15004000 $$
Jumlah yang cukup "berat" untuk dijalankan dengan komputer spek standar. Sebagai solusinya, ditawarkan arsitektur JST yakni CNN yang bisa bekerja dengan mempelajari pola pada skala yang lebih kecil, dan menggunakannya untuk mengidentifikasi gambar yang lebih besar. Contohnya adalah apakah gambar input merupakan gambar singa atau macan. Dengan mempelajari sebagian kecil bagian gambar (misal: bagian mulut), maka informasi tersebut dapat digunakan untuk menentukan gambar yang diinputkan adalah singa atau macan.

Ilustrasi CNN untuk deteksi gambar macan/singa

Konvolusi

Ide dasar dari CNN adalah kovolusi itu sendiri. Jadi, setiap bagian pada image dikonvolusikan dengan kernel atau filter.  Kedua istilah tersebut, filter dan kernel size, pada Keras/Tensorflow dibedakan, filter sebagai representasi banyaknya feature map hasil konvolusi, dan kernel sebagai peng-konvolusi. Sebagai contoh, kita memiliki data image dengan ukuran 5 x 5 pixel, kemudian kita buat filter ukuran 2 x 2. Setiap bagian (2 x 2) pada data image dikonvolusikan dengan kernel atau filter 2 x 2 tadi. Lihat gambar berikut untuk lebih jelasnya.
Related Posts Plugin for WordPress, Blogger...