分享

Py之fasttext:fasttext的简介、安装、案例应用之详细攻略

 处女座的程序猿 2022-11-17 发布于上海

Py之fasttext:fasttext的简介、安装、案例应用之详细攻略


fasttext的简介

fastText是一个用于高效学习单词表示和句子分类的库。

Github官网
GitHub - facebookresearch/fastText: Library for fast text representation and classification.

1、fasttext的原理

     fastText原理有点类似于Word2Vec中CBoW模型,fastText在是实现分类任务中采用了Hierarchical Softmax,突出了两个特性:
(1)、Word2Vec是在输入层得到词向量,输出层对应的 Herarchical Softmax 也会生成一系列的向量,但最终都不会使用。而fastText的输出层对应是分类的label,目的是遍历分类树的所有叶节点,找到概率最大的label。
(2)、Word2Vec的输入是上下文窗口内的词,而fastText 对应的整个文本,包括周边词和 N-Gram的内容。

2、fasttext的功能

(1)、Word representation learning
(2)、Obtaining word vectors for out-of-vocabulary words
(3)、Text classification

fasttext的安装

pip install fasttext

fasttext的案例应用

案例应用https:///project/fasttext/

fasttext:文本分类、训练词向量、词向量迁移_あずにゃん的博客-CSDN博客_pytorch word2vec

1、Word representation model

import fasttext

# Skipgram model :
model = fasttext.train_unsupervised('data.txt', model='skipgram')

# or, cbow model :
model = fasttext.train_unsupervised('data.txt', model='cbow')


print(model.words)   # list of words in dictionary
print(model['king']) # get the vector of the word 'king'


model.save_model("model_filename.bin")
model = fasttext.load_model("model_filename.bin")



2、Text classification model

import fasttext

model = fasttext.train_supervised('data.train.txt')

print(model.words)
print(model.labels)


def print_results(N, p, r):
    print("N\t" + str(N))
    print("P@{}\t{:.3f}".format(1, p))
    print("R@{}\t{:.3f}".format(1, r))

print_results(*model.test('test.txt'))

model.predict("Which baking dish is best to bake a banana bread ?")
model.predict("Which baking dish is best to bake a banana bread ?", k=3)
model.predict(["Which baking dish is best to bake a banana bread ?", "Why not put knives in the dishwasher?"], k=3)


    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章