github中fasttext库README官文文档翻译

参考链接:fastText/python/README.md at main · facebookresearch/fastText (github.com)

fastText模块介绍

fastText 是一个用于高效学习单词表述和句子分类的库。在本文档中,我们将介绍如何在 python 中使用 fastText。

环境要求

fastText 可在现代 Mac OS 和 Linux 发行版上运行。由于它使用了 C++11 功能,因此需要一个支持 C++11 的编译器。您需要 Python(版本 2.7 或 ≥ 3.4)、NumPy & SciPy 和 pybind11。

安装

要安装最新版本,可以执行:

$ pip install fasttext

或者,要获取 fasttext 的最新开发版本,您可以从我们的 github 代码库中安装:

$ git clone https://github.com/facebookresearch/fastText.git
$ cd fastText
$ sudo pip install .
$ # or :
$ sudo python setup.py install

使用概览

词语表征模型

为了像这里描述的那样学习单词向量,我们可以像这样使用 fasttext.train_unsupervised 函数:

import fasttext

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

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

其中,data.txt 是包含 utf-8 编码文本的训练文件。返回的模型对象代表您学习的模型,您可以用它来检索信息。

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

保存和加载模型对象

调用函数 save_model 可以保存训练好的模型对象。

model.save_model("model_filename.bin")

并通过函数 load_model 加载模型参数:

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

文本分类模型

为了使用这里介绍的方法训练文本分类器,我们可以这样使用 fasttext.train_supervised 函数:

import fasttext

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

其中 data.train.txt 是一个文本文件,每行包含一个训练句子和标签。默认情况下,我们假定标签是以字符串 __label__ 为前缀的单词。模型训练完成后,我们就可以检索单词和标签列表:

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

为了通过在测试集上计算精度为 1 (P@1) 和召回率来评估我们的模型,我们使用了测试函数:

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 ?")

默认情况下,predict 只返回一个标签:概率最高的标签。您也可以通过指定参数 k 来预测多个标签:

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)

当然,您也可以像文字表示法那样,将模型保存到文件或从文件加载模型。

用量化技术压缩模型文件

当您想保存一个经过监督的模型文件时,fastText 可以对其进行压缩,从而只牺牲一点点性能,获得更小的模型文件。

# with the previously trained `model` object, call :
model.quantize(input='data.train.txt', retrain=True)

# then display results and save the new model :
print_results(*model.test(valid_data))
model.save_model("model_filename.ftz")

model_filename.ftz 的大小将远远小于 model_filename.bin。

重要:预处理数据/编码约定

一般来说,对数据进行适当的预处理非常重要。特别是根文件夹中的示例脚本可以做到这一点。

fastText 假定使用 UTF-8 编码的文本。对于 Python2,所有文本都必须是 unicode;对于 Python3,所有文本都必须是 str。传入的文本将由 pybind11 编码为 UTF-8,然后再传给 fastText C++ 库。这意味着在构建模型时,使用 UTF-8 编码的文本非常重要。在类 Unix 系统中,可以使用 iconv 转换文本。

fastText 将根据以下 ASCII 字符(字节)进行标记化(将文本分割成片段)。特别是,它无法识别 UTF-8 的空白。我们建议用户将UTF-8 空格/单词边界转换为以下适当的符号之一。

空间
选项卡
垂直制表符
回车
换页
空字符

换行符用于分隔文本行。特别是,如果遇到换行符,EOS 标记就会被附加到文本行中。唯一的例外情况是,标记的数量超过了字典标题中定义的 MAX_LINE_SIZE 常量。这意味着,如果文本没有换行符分隔,例如 fil9 数据集,它将被分割成具有 MAX_LINE_SIZE 的标记块,而 EOS 标记不会被附加。

标记符的长度是UTF-8 字符的数量,通过考虑字节的前两位来识别多字节序列的后续字节。在选择子字的最小和最大长度时,了解这一点尤为重要。此外,EOS 标记(在字典标头中指定)被视为一个字符,不会被分解为子字。

更多实例

为了更好地了解 fastText 模型,请参阅主 README,特别是我们网站上的教程。您还可以在 doc 文件夹中找到更多 Python 示例。与其他软件包一样,您可以使用 help 函数获得有关任何 Python 函数的帮助。

例如

+>>> import fasttext
+>>> help(fasttext.FastText)

Help on module fasttext.FastText in fasttext:

NAME
    fasttext.FastText

DESCRIPTION
    # Copyright (c) 2017-present, Facebook, Inc.
    # All rights reserved.
    #
    # This source code is licensed under the MIT license found in the
    # LICENSE file in the root directory of this source tree.

FUNCTIONS
    load_model(path)
        Load a model given a filepath and return a model object.

    tokenize(text)
        Given a string of text, tokenize it and return a list of tokens
[...]

API——应用程序接口

train_unsupervised (无监督训练参数)

    input             # training file path (required)
    model             # unsupervised fasttext model {cbow, skipgram} [skipgram]
    lr                # learning rate [0.05]
    dim               # size of word vectors [100]
    ws                # size of the context window [5]
    epoch             # number of epochs [5]
    minCount          # minimal number of word occurences [5]
    minn              # min length of char ngram [3]
    maxn              # max length of char ngram [6]
    neg               # number of negatives sampled [5]
    wordNgrams        # max length of word ngram [1]
    loss              # loss function {ns, hs, softmax, ova} [ns]
    bucket            # number of buckets [2000000]
    thread            # number of threads [number of cpus]
    lrUpdateRate      # change the rate of updates for the learning rate [100]
    t                 # sampling threshold [0.0001]
    verbose           # verbose [2]

train_supervised parameters(监督训练参数)

    input             # training file path (required)
    lr                # learning rate [0.1]
    dim               # size of word vectors [100]
    ws                # size of the context window [5]
    epoch             # number of epochs [5]
    minCount          # minimal number of word occurences [1]
    minCountLabel     # minimal number of label occurences [1]
    minn              # min length of char ngram [0]
    maxn              # max length of char ngram [0]
    neg               # number of negatives sampled [5]
    wordNgrams        # max length of word ngram [1]
    loss              # loss function {ns, hs, softmax, ova} [softmax]
    bucket            # number of buckets [2000000]
    thread            # number of threads [number of cpus]
    lrUpdateRate      # change the rate of updates for the learning rate [100]
    t                 # sampling threshold [0.0001]
    label             # label prefix ['__label__']
    verbose           # verbose [2]
    pretrainedVectors # pretrained word vectors (.vec file) for supervised learning []

模型对象、

train_supervised、train_unsupervised 和 load_model 函数返回 _FastText 类的一个实例,我们一般将其命名为模型对象。

该对象将这些训练参数作为属性公开:lr、dim、ws、epoch、minCount、minCountLabel、minn、maxn、neg、wordNgrams、loss、bucket、thread、lrUpdateRate、t、label、verbose、pretrainedVectors。因此,model.wordNgrams 将给出用于训练该模型的单词 ngram 的最大长度。

此外,该对象还公开了多个函数:

    get_dimension           # Get the dimension (size) of a lookup vector (hidden layer).
                            # This is equivalent to `dim` property.
    get_input_vector        # Given an index, get the corresponding vector of the Input Matrix.
    get_input_matrix        # Get a copy of the full input matrix of a Model.
    get_labels              # Get the entire list of labels of the dictionary
                            # This is equivalent to `labels` property.
    get_line                # Split a line of text into words and labels.
    get_output_matrix       # Get a copy of the full output matrix of a Model.
    get_sentence_vector     # Given a string, get a single vector represenation. This function
                            # assumes to be given a single line of text. We split words on
                            # whitespace (space, newline, tab, vertical tab) and the control
                            # characters carriage return, formfeed and the null character.
    get_subword_id          # Given a subword, return the index (within input matrix) it hashes to.
    get_subwords            # Given a word, get the subwords and their indicies.
    get_word_id             # Given a word, get the word id within the dictionary.
    get_word_vector         # Get the vector representation of word.
    get_words               # Get the entire list of words of the dictionary
                            # This is equivalent to `words` property.
    is_quantized            # whether the model has been quantized
    predict                 # Given a string, get a list of labels and a list of corresponding probabilities.
    quantize                # Quantize the model reducing the size of the model and it's memory footprint.
    save_model              # Save the model to the given path
    test                    # Evaluate supervised model using file given by path
    test_label              # Return the precision and recall score for each label.    

属性 words, labels 返回字典中的单词和标签:

model.words         # equivalent to model.get_words()
model.labels        # equivalent to model.get_labels()

该对象重载了 __getitem__ 和 __contains__ 函数,以便返回单词的表示形式和检查单词是否在词汇表中

model['king']       # equivalent to model.get_word_vector('king')
'king' in model     # equivalent to `'king' in model.get_words()`

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/585757.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

力扣153. 寻找旋转排序数组中的最小值

Problem: 153. 寻找旋转排序数组中的最小值 文章目录 题目描述思路复杂度Code 题目描述 思路 1.初始化左右指针left和right,指向数组的头和尾; 2.开始二分查找: 2.1.定义退出条件:当left right时退出循环; 2.2.当nums…

【会员单位】浙江晧月水务科技有限公司

中华环保联合会理事单位 水环境治理专业委员会副主任委员单位 公司成立于2018年3月14日,是专业研究废水处理业务的国家高新技术企业。 公司自主研发的脱硫废水“零排放”的技术,不仅适应性好,技术先进,智慧化程度高&#xff0c…

深度学习中的变形金刚——transformer

很荣幸能和这些大牛共处一个时代。网络结构名字可以是一个卡通形象——变形金刚,论文名字可以来源于一首歌——披头士乐队的歌曲《All You Need Is Love》。 transformer在NeurIPS2017诞生,用于英语-德语,英语-法语的翻译,在BLEU…

21 如何进行高保真压测和服务扩容?

在后台架构中,压测非常常见,也是必须的工作。它能够帮我们发现微服务架构中的性能瓶颈,以及知道构建的微服务能承载的流量极限值。 但实际情况是,很多压测并不能发现瓶颈点和微服务所能承载的真实流量极限值。一方面是因为压测时…

LiveGBS user/save 逻辑缺陷漏洞复现(CNVD-2023-72138)

0x01 产品简介 LiveGBS是安徽青柿信息科技有限公司研发的一款国标(GB28181)流媒体服务软件,可提供提供用户管理及Web可视化页面管理,开源的前端页面源码;提供设备状态管理,可实时查看设备是否掉线等信息等。 0x02 漏洞概述 LiveGBS user/save 接口处存在逻辑缺陷漏洞,未…

【Qt之OpenGL】01创建OpenGL窗口

1.创建子类继承QOpenGLWidget 2.重写三个虚函数 /** 设置OpenGL的资源和状态,最先调用且调用一次* brief initializeGL*/ virtual void initializeGL() override; /** 设置OpenGL视口、投影等,当widget调整大小(或首次显示)时调用* brief resizeGL* param w* para…

请求接口报错:java.lang.IllegalStateException: argument type mismatch

目录 一、场景二、报错信息三、控制器四、接口调用五、原因六、解决 一、场景 1、调用后端接口报错 2、接口参数以Json方式传递 – 二、报错信息 java.lang.IllegalStateException: argument type mismatch Controller [com.xxx.huarunshouzheng.controller.MallControlle…

Ubuntu如何更换 PyTorch 版本

环境: Ubuntu22.04 WLS2 问题描述: Ubuntu如何更换 PyTorch 版本考虑安装一个为 CUDA 11.5 编译的 PyTorch 版本。如何安装旧版本 解决方案: 决定不升级CUDA版本,而是使用一个与CUDA 11.5兼容的PyTorch版本,您可…

75、堆-前K个高频元素

思路 这道题还是使用优先队列,是要大根堆,然后创建一个类,成员变量值和次数。大根堆基于次数排序。前k个就拿出前k的类的值即可。代码如下: class Solution {public int[] topKFrequent(int[] nums, int k) {if (nums null || …

解决: 0x803f7001 在运行Microsoft Windows 非核心版本的计算机上,运行“ slui.exe 0x2a 0x803f7001 “以显示错误文本,激活win10步骤流程。

一. 解决 0x803F7001在运行Microsoft Windows非核心版本的计算机错误 首先,按下winR打开"运行",输入 regedit 后回车,打开注册表。   然后再注册表下输入地址HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProt…

Electron+Vue3+Vite+ElectronForge整合 - 一键启动两个服务 一键打包两个服务

说明 本文介绍一下 Electron Vue3 Vite Electron Forge 的高级整合操作。vue3 : 使用 TS 的语法开发; Electron : 使用 JS 的语法开发。本文将从项目初始化开始,一步一步的完成项目的启动、打包全流程的介绍。实现的效果是 : 1、一个正常…

一个类实现Mybatis的SQL热更新

引言 平时用SpringBootMybatis开发项目,如果项目比较大启动时间很长的话,每次修改Mybatis在Xml中的SQL就需要重启一次。假设项目重启一次需要5分钟,那修改10次SQL就过去了一个小时,成本有点太高了。关键是每次修改完代码之后再重…

前端打包过大如何解决?

前端开发完毕部署到线上是,执行npm run build。当打包过大时,部署到服务端后加载缓慢,如何优化? 我们可以通过执行npm run analyze。可以看到各个包文件大小的区别。 当打包过大时,通过压缩gzip的方式,可以…

React路由导航

1. 什么是路由导航 一个路由跳转到另一个路由&#xff0c;并且在跳转的同时有可能需要传递参数进行通信&#xff0c;比如列表页跳转到详情页携带参数 2. 声明式导航 声明式导航是指通过在模版中通过 <Link/> 组件描述出要跳转到哪里去&#xff0c;比如后台管理系统的…

【LeetCode】---15.最小栈

【LeetCode】---15.最小栈 一、题目解析&#xff1a;二、算法原理&#xff1a;三、代码实现&#xff1a; 一、题目解析&#xff1a; 设计一个支持 push &#xff0c;pop &#xff0c;top 操作&#xff0c;并能在常数时间内检索到最小元素的栈。 实现 MinStack 类: MinStack() 初…

ARP学习及断网攻击

1.什么是ARP ARP&#xff08;Address Resolution Protocol&#xff09;是一种用于在IPv4网络中将IP地址映射到MAC地址的协议。在计算机网络中&#xff0c;每个网络接口都有一个唯一的MAC地址&#xff08;Media Access Control address&#xff09;&#xff0c;用于识别网络设备…

形态学图像处理

首先自己随便写了一个单词&#xff0c;然后在周围画一些相对细一点的噪声。 # 读取原始图片 original cv2.imread("romance.jpg") # 构造一个全1的5*5矩阵 kernel np.ones((5, 5), np.int8) 腐蚀 腐蚀&#xff08;Erosion&#xff09;是形态学图像处理中的一种基本…

Linux操作系统·进程管理

一、什么是进程 1.作业和进程的概念 Linux是一个多用户多任务的操作系统。多用户是指多个用户可以在同一时间使用计算机系统&#xff1b;多任务是指Linux可以同时执行几个任务&#xff0c;它可以在还未执行完一个任务时又执行另一项任务。为了完成这些任务&#xff0c;系统上…

初识Linux -- Linux的背景和发展史介绍

点赞关注不迷路&#xff01;&#xff0c;本节涉及初识Linux&#xff0c;主要为背景介绍和xshell登录主机。 1.Linux背景 1.1 发展史 Linux从哪里来&#xff1f;它是怎么发展的&#xff1f;在这里简要介绍Linux的发展史。 要说Linux&#xff0c;还得从UNIX说起。 1.2 UNIX发…

水下机器人(ROV)中继器(TMS)究竟是个啥?

前段时间公众号后台有人问释放ROV的装置&#xff0c;由于只用过观察级ROV Valor&#xff0c;博主一直以为他说的是绞车&#xff0c;后来才明白他说的是中继器&#xff0c;在水中用来释放、控制和回收ROV的装置。 中继器TMS的全称是缆绳管理系统Tether Management System&#…
最新文章