Word2vec教程

Word2vec TutorialRADIM ŘEHŮŘEK2014-02-02GENSIM,PROGRAMMING157 COMMENTSI never got round to writing a tutorial on how to use word2vec in gensim. It’s simple enough and theAPI docsare stra...
摘要由CSDN通过智能技术生成

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()
 
s
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值