Word2vec教程

这篇教程详细介绍了如何使用gensim库进行Word2vec训练。从输入数据的准备到模型训练,再到模型评估、存储和加载,以及在线训练和使用模型。文章还提供了关于内存管理和评估指标的说明,并给出了一个简单的Python代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Word2vec Tutorial

 RADIM ŘEHŮŘEK 2014-02-02 GENSIM PROGRAMMING 157 COMMENTS

I never got round to writing a tutorial on how to use word2vec in gensim. It’s simple enough and the API docs are straightforward, but I know some people prefer more verbose formats. Let this post be a tutorial and a reference example.

UPDATE: the complete HTTP server code for the interactive word2vec demo below is now open sourced on Github. For a high-performance similarity server for documents, see ScaleText.com.

Preparing the Input

Starting from the beginning, gensim’s word2vec expects a sequence of sentences as its input. Each sentence a list of words (utf8 strings):

1
2
3
4
5
6
7
# import modules & set up logging
import gensim, logging
logging.basicConfig( format = '%(asctime)s : %(levelname)s : %(message)s' , level = logging.INFO)
 
sentences = [[ 'first' , 'sentence' ], [ 'second' , 'sentence' ]]
# train word2vec on the two sentences
model = gensim.models.Word2Vec(sentences, min_count = 1 )

Keeping the input as a Python built-in list is convenient, but can use up a lot of RAM when the input is large.

Gensim only requires that the input must provide sentences sequentially, when iterated over. No need to keep everything in RAM: we can provide one sentence, process it, forget it, load another sentence…

For example, if our input is strewn across several files on disk, with one sentence per line, then instead of loading everything into an in-memory list, we can process the input file by file, line by line:

1
2
3
4
5
6
7
8
9
10
11
class MySentences( object ):
     def __init__( self , dirname):
         self .dirname = dirname
 
     def __iter__( self ):
         for fname in os.listdir( self .dirname):
             for line in open (os.path.join( self .dirname, fname)):
                 yield line.split()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值