美文网首页
2.2 语言模型和词向量 tensorflow词向量

2.2 语言模型和词向量 tensorflow词向量

作者: lbda1 | 来源:发表于2018-01-08 18:11 被阅读0次

    ----------------------------大纲--------------------------

    1 随着模型不断更新

    2 直接使用预先训练好的词向量如word2vec, glove

    --------------------------------------------------------------

    省去数据读取以及预处理模块

    1 随着模型不断更新

    1.1 train文件中输入语句用index表示

    #表示最长的句子长度max_document_length

    max_document_length=max([len(x.split(" "))for xin x_text])

    vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)

    #拿到句子中的index向量表示(注意这里是词的index)

    x = list(vocab_processor.fit_transform(x_text))

    1.2 模型文件中index向量转化为词向量

    self.input_x = tf.placeholder(tf.int32, [None, sequence_length],name="input_x")

    with tf.name_scope("embedding"):

    #tf.random_uniform([vocab_size, embedding_size], -1.0,1.0)词向量采用均匀分布作为初始化

    # trainable=Ture表示模型中不断迭代更新词向量的值,如果trainable=False表示采用第三方预先训练好的词向量结果

    self.W = tf.Variable(tf.random_uniform([vocab_size, embedding_size], -1.0,1.0),trainable=True, name="W")

    self.embedded_x = tf.nn.embedding_lookup(self.W,self.input_x)

    2 直接使用预先训练好的词向量如word2vec, glove

    如下以glove为例,格式如下,词以及其对应的词向量

    2.1 train文件中

    # 读文件获取glove中的词汇,以及其对应的词向量

    vocab, embd = data_helpers.loadGloVe(FLAGS.embedding_file, FLAGS.embedding_dim)

    embedding = np.asarray(embd)

    def tokenizer(iterator):

        for value in iterator:

            yield re.split(r'\s', value)

    # 将glove文件中的词转化为index

    vocab_processor = learn.preprocessing.VocabularyProcessor(max_sequence_length, tokenizer_fn=tokenizer)

    vocab_processor.fit(vocab)

    #拿到句子中的index向量表示(注意这里是词的index)

    x = list(vocab_processor.fit_transform(x_text))

    2.2 model文件中

    #传入glove的初始值的占位符

    self.embedding_placeholder = tf.placeholder(tf.float32, [self.vocab_size,self.embedding_size],

    name="embedding")

    self.input_x = tf.placeholder(tf.int32, [None, sequence_length],name="input_x")

    with tf.variable_scope("embedding"):

    #trainable=False的设置如上

           self.W = tf.Variable(tf.constant(0.0,shape=[self.vocab_size,self.embedding_size]),                     trainable=False, name="W")

    # 把glove初始值给self.W

    self.embedding_init = tf.assign(self.W,self.embedding_placeholder)

    self.embedded_x = tf.nn.embedding_lookup(self.W,input_x )

    相关文章

      网友评论

          本文标题:2.2 语言模型和词向量 tensorflow词向量

          本文链接:https://www.haomeiwen.com/subject/pinbnxtx.html