Closed7

fastTextのインタフェース調査

yagiyukiyagiyuki

fastTextインストールに必要なパッケージ

# apt-get install -y cmake wget vim

fastTextインストール

# wget https://github.com/facebookresearch/fastText/archive/v0.9.2.zip
# unzip v0.9.2.zip
# cd fastText-0.9.2/
# mkdir build && cd build && cmake ..
# make && make install
# ls -tlr /usr/local/lib/*fast*
-rw-r--r-- 1 root root 868130 May  2 10:09 /usr/local/lib/libfasttext.a
-rw-r--r-- 1 root root 523552 May  2 10:09 /usr/local/lib/libfasttext.so.0
-rw-r--r-- 1 root root 833852 May  2 10:09 /usr/local/lib/libfasttext_pic.a
lrwxrwxrwx 1 root root     16 May  2 10:09 /usr/local/lib/libfasttext.so -> libfasttext.so.0

python版のfastText

# cd fastText-0.9.2/
# pip install .
# python 
Python 3.7.10 (default, Apr 10 2021, 16:02:25)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fasttext # fastTextがimportできることを確認
yagiyukiyagiyuki

データセットの取得

wget https://dl.fbaipublicfiles.com/fasttext/data/cooking.stackexchange.tar.gz && tar xvzf cooking.stackexchange.tar.gz

データ分割

head -n 12404 cooking.stackexchange.txt > cooking.train
tail -n 3000 cooking.stackexchange.txt > cooking.valid
yagiyukiyagiyuki

モデルのハイパーパラメータ情報

root@3808269892f8:/home# fasttext dump model_cooking.bin args
dim 100
ws 5
epoch 5
minCount 1
neg 5
wordNgrams 1
loss softmax
model sup
bucket 0
minn 0
maxn 0
lrUpdateRate 100
t 0.0001
yagiyukiyagiyuki

各種インタフェース

C++

fasttext supervised -input data/cooking.train -epoch 5 -output model_cooking
fasttext predict model_cooking.bin data/cooking.valid > predicted_label.valid

python

>>> model = fasttext.train_supervised(input='data/cooking.train')
Read 0M words
Number of words:  14543
Number of labels: 735
Progress: 100.0% words/sec/thread:  106490 lr:  0.000000 avg.loss: 10.076416 ETA:   0h 0m 0s
>>> model.save_model('model_cooking_py.bin')
>>> model = fasttext.load_model('model_cooking_py.bin')
Warning : `load_model` does not return WordVectorModel or SupervisedModel any more, but a `FastText` object which is very similar.
>>> model.predict(["aaa"])
([['__label__food-safety']], [array([0.5619119], dtype=float32)])
yagiyukiyagiyuki

C++をIFを直接呼び出したい場合は、以下のコードを編集すればよい。
https://github.com/facebookresearch/fastText/blob/master/src/main.cc

Makefileのサンプル

# (1)コンパイラ
CC  = g++
# (2)コンパイルオプション
CFLAGS    =
# (3)実行ファイル名
TARGET  = cfasttext
# (4)コンパイル対象のソースコード
SRCS    = *.cpp
# (5)オブジェクトファイル名
OBJS    = $(SRCS:.cpp=.o)

# (6)インクルードファイルのあるディレクトリパス
INCDIR  = -I../usr/local/include/fasttext/

# (7)ライブラリファイルのあるディレクトリパス
LIBDIR  = -L/usr/local/lib/

# (8)追加するライブラリファイル
LIBS    = -lfasttext

# (9)ターゲットファイル生成
$(TARGET): $(OBJS)
	$(CC) -o $@ $^ $(LIBDIR) $(LIBS)

# (10)オブジェクトファイル生成
$(OBJS): $(SRCS)
	$(CC) $(CFLAGS) $(INCDIR) -c $(SRCS)

# (11)"make all"で make cleanとmakeを同時に実施。
all: clean $(OBJS) $(TARGET)
# (12).oファイル、実行ファイル、.dファイルを削除
clean:
	-rm -f $(OBJS) $(TARGET) *.d
このスクラップは2021/05/07にクローズされました