1. 程式人生 > >Language Model perplexity by using tensorflow使用tensorflow RNN模型計算語言模型的困惑度

Language Model perplexity by using tensorflow使用tensorflow RNN模型計算語言模型的困惑度

LM perplexity by using tensorflow

1、Language model perplexity是衡量語言模型好壞的重要指標,其計算公式P(sentence)^-(1/N)

2、tensorflow的RNN模型如何使用
參考API文件:tf.contrib.legacy_seq2seq.sequence_loss_by_example,這個函式會返回一個大小為N的列表,N為句子數目,每個值代表該句話的log-perplexity。

tf.contrib.legacy_seq2seq.sequence_loss_by_example(
    logits,
    targets,
    weights,
    average_across_timesteps=True
, softmax_loss_function=None, name=None )
#計算這個batch的log-perplexity,返回的是shape=[batch]的值,代表每個句子的log-perplexity
loss = legacy_seq2seq.sequence_loss_by_example([self.logits],
                [tf.reshape(self.targets, [-1])],
                [tf.ones([args.batch_size * args.seq_length])],
                args.vocab
_size) #計算這個batch中所有句子的平均log-perplexity self.cost = tf.reduce_sum(loss) / args.batch_size #計算這個batch中所有句子的平均perplexity self.perplexity = tf.exp(self.cost)

可以看一下tensorflow對sequence_loss_by_example的原始碼

def sequence_loss_by_example(logits,
                             targets,
                             weights,
                             average_across_timesteps=True,
                             softmax_loss_function=None,
                             name=None)
:
"""Weighted cross-entropy loss for a sequence of logits (per example). Args: logits: List of 2D Tensors of shape [batch_size x num_decoder_symbols]. targets: List of 1D batch-sized int32 Tensors of the same length as logits. weights: List of 1D batch-sized float-Tensors of the same length as logits. average_across_timesteps: If set, divide the returned cost by the total label weight. softmax_loss_function: Function (labels-batch, inputs-batch) -> loss-batch to be used instead of the standard softmax (the default if this is None). name: Optional name for this operation, default: "sequence_loss_by_example". Returns: 1D batch-sized float Tensor: The log-perplexity for each sequence. Raises: ValueError: If len(logits) is different from len(targets) or len(weights). """ if len(targets) != len(logits) or len(weights) != len(logits): raise ValueError("Lengths of logits, weights, and targets must be the same " "%d, %d, %d." % (len(logits), len(weights), len(targets))) with ops.name_scope(name, "sequence_loss_by_example", logits + targets + weights): log_perp_list = [] for logit, target, weight in zip(logits, targets, weights): if softmax_loss_function is None: # TODO(irving,ebrevdo): This reshape is needed because # sequence_loss_by_example is called with scalars sometimes, which # violates our general scalar strictness policy. target = array_ops.reshape(target, [-1]) crossent = nn_ops.sparse_softmax_cross_entropy_with_logits( labels=target, logits=logit) else: crossent = softmax_loss_function(target, logit) log_perp_list.append(crossent * weight) log_perps = math_ops.add_n(log_perp_list) if average_across_timesteps: total_size = math_ops.add_n(weights) total_size += 1e-12 # Just to avoid division by 0 for all-0 weights. log_perps /= total_size return log_perps

計算的過程是:
1、求句子的每個時間點(RNN timestep)處的loss,然後對每個時間點的loss求和。
2、求句子的長度(timestep),然後loss/timestep。(預設需要對average_across_timesteps )

相關推薦

Language Model perplexity by using tensorflow使用tensorflow RNN模型計算語言模型困惑

LM perplexity by using tensorflow 1、Language model perplexity是衡量語言模型好壞的重要指標,其計算公式P(sentence)^-(1/N) 2、tensorflow的RNN模型如何使用 參考API

Language model】使用RNN LSTM訓練語言模型 寫出45°角仰望星空的文章

開篇 這篇文章主要是實戰內容,不涉及一些原理介紹,原理介紹為大家提供一些比較好的連結:   1. Understanding LSTM Networks : RNN與LSTM最為著名的文章,貼圖和內容都恰到好處,為研究人員提供很好的參考價值。 中文漢化版:(譯

LightRNN —— 基於RNN的輕量級語言模型

2017年6月我在MSRA實習的時候,在微軟內部的Talk上聽過MSRA主管研究員秦濤博士講過一篇他們團隊在2016年頂會NIPS上發表的最新成果《LightRNN: Memory and Computation-Efficient Recurrent Neur

[NLP]使用LDA模型計算文件相似

定義 wiki關於lda的定義: 隱含狄利克雷分佈簡稱LDA(Latent Dirichlet allocation),是一種主題模型,它可以將文件集中每篇文件的主題按照概率分佈的形式給出。同時它是一種無監督學習演算法,在訓練時不需要手工標註的訓練集,需要的

語言模型RNN CS244n 大作業 Natural Language Processing

語言模型 語言模型能夠計算一段特定的字詞組合出現的頻率, 比如:”the cat is small” 和 “small the is cat”, 前者出現的頻率高 同樣的,根據前面所有的字詞序列資訊, 我們可以確定下一個位置某個特定詞出現的頻率, 豎線左邊表示下一個出現詞

Coding Brain Neurons by using Hodgkin-Huxley model

Understanding how the human brain w

Statistical language model 統計語言模型

我們能夠建立語言模型了,一般的我們在訓練集上得到語言模型的引數,在測試集裡面來測試模型的效能,那麼如何去衡量一個語言模型的好壞呢?比較兩個模型A,B好壞,一種外在的評價就是將AB放入具體的任務中,然後分別得到模型的準確率,這種方式當然是最好的方式,但這種方式的缺點是過於耗時,在實際情況中往往需要花費過多時間才

The Struts dispatcher cannot be found. This is usually caused by using Struts

without through san sans word needed ice ffffff per 對於struts2中的問題: org.apache.jasper.JasperException: The Struts dispatcher cannot be fou

[TypeScript] Shallow copy object by using spread opreator

cnblogs not all som htm div target oid html For example we have an object: const todo = { text: "Water the flowers", completed:

sru源碼--language model

紀元 range rds new format avg learn ber form import sys import os import argparse import time import random import math import numpy as n

[MST] Restore the Model Tree State using Hot Module Reloading when Model Definitions Change

component function efi .get stat set sna mode you n this lesson, we will set up Hot Module Reloading(HMR), making it possible to load

[Tools] Create your own mobile emulator device by using Chrome dev tool

mobile info tom rom ng- hang ima drop-down inf Using the New Device Emulation Interface The Device Emulation interface changed a bit wit

[Angular] Increasing Performance by using Pipe

PE sin call food nbsp anything actually foo inpu For example you make a function to get rating; getRating(score: number): string {

mysql group by using filesort優化

str markdown pan down rom logs pre _id clas 原join 連接語句SELECT SUM(video_flowers.number) AS num,video_flowers.flower_id,flowers.title,flowe

type Exception report message The Struts dispatcher cannot be found. This is usually caused by using

1.解決方法 將web.xml 的過濾器,從 .action 修改為: / <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-insta

RNN實現字元級語言模型 - 恐龍島_g

問題描述:樣本為所有恐龍名字,為了構建字元級語言模型來生成新的名稱,你的模型將學習不同的名稱模式,並隨機生成新的名字。 在這裡你將學習到: 如何儲存文字資料以便使用rnn進行處理。 如何合成數據,通過每次取樣預測,並將其傳遞給下一個rnn單元。 如何構建字元級文字生成迴圈神經網路。 為

一文詳解NGram語言模型以及困惑perplexity

  歡迎關注“勇敢AI”公眾號,更多python學習、資料分析、機器學習、深度學習原創文章與大家分享,還有更多電子資源、教程、資料集下載。勇敢AI,一個專注於人工智慧AI的公眾號。 ==========================================

A CONVERSATIONAL NEURAL LANGUAGE MODEL FOR SPEECH RECOGNITION IN DIGITAL ASSISTANTS文獻閱讀筆記

摘要:對話序列有利於提高數字助手(可以理解為手機的siri,微軟小冰等)的能力,我們探索了神經網路語言模型模擬數字助手的對話。我們提出的結果可以有效刻畫對話特徵,在識別率上相對提高了%4. 1.     不同於其他領域的語音識別,數字助手主要為對話形式的。所以應該建立一個

吳恩達 第四課第一週 程式設計 Convolution model - Step by Step - v2

  Convolutional Neural Networks: Step by Step Welcome to Course 4's first assignment! In this assignment, you will implement convolutional (C

使用 rnn 訓練詞向量模型

詞向量說明如下: 詞向量模型表徵的是詞語與詞語之間的距離和聯絡,詞向量也叫詞嵌入 word embedding CBOW 模型: 根據某個詞的上下文,計算中間詞出現的概率,預測的是中心詞 Skip-Gram 模型: 跟據中間詞,分別計算它的上下文概率,與 CBOW 模型相反