11句對匹配實戰(zhàn)-(1)Siamese

用的是kaggle上的比賽“Quora Question Paris: Can you identify question pairs that have the same intent?”
評估指數(shù): log loss
測試集:

  • 大惺嗵:40.4萬
  • 屬性:6列,分別是id, qid1, question1, question2, is_duplicate
    測試集:
  • 大屑崆ⅰ:235萬
  • 屬性:3列凿跳,分別是test_id, qeustion1, question2

這里用到的第一個方法是孿生網(wǎng)絡(luò) Siamese Network,白話點就是我要看看這兩個句子是否一樣秒裕,就將兩個輸入feed進兩個神經(jīng)網(wǎng)絡(luò),word embedding后虎眨,通過Loss的計算叮姑,評價兩個輸入的相似度。

image.png
上圖可以看出院塞,左右兩邊可以是一個神經(jīng)網(wǎng)絡(luò)(如都是CNN)遮晚,也可以是不同的(一個LSTM,一個CNN),但是兩邊的權(quán)重值一樣性昭。關(guān)于loss,softmax是一種好的選擇拦止,但不一定是最優(yōu)的。siamese網(wǎng)絡(luò)的初衷是計算兩個輸入的相似度糜颠,可以簡單點汹族,直接求embedding向量的cosine值就好。

在之前word embedding中有提到cosine值是計算兩個向量的夾角來判斷兩個詞的相似性其兴,那么句子了顶瞒?段落了?可以用exp保留兩個向量的長度信息(見下圖)


image.png

兩邊都用了LSTM,仔細看下LSTMa一開始是不知道LSTMb的存在元旬,直到進行到h3(a)時榴徐,才會和LSTMb中的h4(b)進行匹配。h3-h4用曼哈頓距離來度量兩個句子的空間相似度匀归。

當兩邊都是LSTM時

with tf.name_scope('embeddings'):
    self._m_token_embeddings = tf.Variable(
        tf.truncated_normal(
            [self._m_config["vocab_size"], self._m_config["embedding_dim"]],
            stddev=0.1
        ),
        name="token_embeddings"
    )
    embedded_sent1 = tf.nn.embedding_lookup(self._m_token_embeddings, self._m_ph_sent1)
    embedded_sent2 = tf.nn.embedding_lookup(self._m_token_embeddings, self._m_ph_sent2)
self._m_embedded_sent1 = embedded_sent1

with tf.name_scope('lstm_layer'):
    cell1 = tf.nn.rnn_cell.LSTMCell(
        self._m_config["lstm_dim"],
        state_is_tuple=True,
        reuse=tf.AUTO_REUSE
    )
    cell2 = tf.nn.rnn_cell.LSTMCell(
        self._m_config["lstm_dim"],
        state_is_tuple=True,
        reuse=tf.AUTO_REUSE
    )
    _, (_, output_cell1) = tf.nn.dynamic_rnn(
        cell1, embedded_sent1, dtype=tf.float32, sequence_length=self._m_ph_sent1_size)
    _, (_, output_cell2) = tf.nn.dynamic_rnn(
        cell1, embedded_sent2, dtype=tf.float32, sequence_length=self._m_ph_sent2_size)

with tf.name_scope("feature_mapping"):
    sent_diff = output_cell1 - output_cell2
    sent_mul = tf.multiply(output_cell1, output_cell2)
    features = tf.concat([sent_diff, sent_mul, output_cell1, output_cell2], axis=1)

    W = tf.Variable(tf.truncated_normal(
                    shape=[self._m_config["lstm_dim"] * 4, self._m_config["label_num"]],
                    stddev=0.1, mean=0.0))
    b = tf.Variable(tf.truncated_normal(
                    shape=[self._m_config["label_num"]], stddev=0.1, mean=0.0))
    self._m_logits = tf.nn.xw_plus_b(features, W, b)

with tf.name_scope("loss"):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(
                        labels=self._m_ph_label, logits=self._m_logits)
    self._m_loss = tf.reduce_mean(cross_entropy)

with tf.name_scope("accuracy"):
    self._m_prediction = tf.argmax(self._m_logits, axis=1)
    correct = tf.equal(self._m_prediction, tf.argmax(self._m_ph_label, axis=1))
    self._m_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))

with tf.name_scope("optimizer"):
    self._m_global_step = tf.Variable(0, name="global_step", trainable=False)
    self._m_optimizer = tf.train.AdamOptimizer(self._m_config["learning_rate"])
    self._m_train_op = self._m_optimizer.minimize(
                            self._m_loss, global_step=self._m_global_step)

當兩邊都用CNN時

with tf.name_scope('embeddings'):
    self._m_token_embeddings = tf.Variable(
        tf.truncated_normal(
            [self._m_config["vocab_size"], self._m_config["embedding_dim"]],
            stddev=0.1
        ),
        name="token_embeddings"
    )
    embedded_sent1 = tf.nn.embedding_lookup(self._m_token_embeddings, self._m_ph_sent1)
    embedded_sent2 = tf.nn.embedding_lookup(self._m_token_embeddings, self._m_ph_sent2)

    dropout_embedded_sent1 = tf.nn.dropout(embedded_sent1, keep_prob=self._m_ph_keep_prob)
    dropout_embedded_sent2 = tf.nn.dropout(embedded_sent2, keep_prob=self._m_ph_keep_prob)

with tf.name_scope('sentence_features'):
    sent1_features = self._build_conv_features(dropout_embedded_sent1)
    sent2_features = self._build_conv_features(dropout_embedded_sent2)
    #dropout_sent1_features = tf.nn.dropout(sent1_features, keep_prob=self._m_ph_keep_prob)
    #dropout_sent2_features = tf.nn.dropout(sent2_features, keep_prob=self._m_ph_keep_prob)
    dropout_sent1_features = tf.identity(sent1_features)
    dropout_sent2_features = tf.identity(sent2_features)

with tf.name_scope("feature_mapping"):
    sent_diff = dropout_sent1_features - dropout_sent2_features
    sent_mul = tf.multiply(dropout_sent1_features, dropout_sent2_features)
    features = tf.concat([sent_diff, sent_mul, dropout_sent1_features, dropout_sent2_features], axis=1)
    dropout_features = tf.nn.dropout(features, keep_prob=self._m_ph_keep_prob)

    cnn_feature_num = self._m_config["num_filters"] * len(self._m_config["filter_sizes"])
    W = tf.Variable(tf.truncated_normal(
                    shape=[cnn_feature_num * 4, self._m_config["label_num"]],
                    stddev=0.1, mean=0.0))
    b = tf.Variable(tf.truncated_normal(
                    shape=[self._m_config["label_num"]], stddev=0.1, mean=0.0))
    self._m_logits = tf.nn.xw_plus_b(features, W, b)

with tf.name_scope("loss"):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(
                        labels=self._m_ph_label, logits=self._m_logits)
    self._m_loss = tf.reduce_mean(cross_entropy)

with tf.name_scope("accuracy"):
    self._m_prediction = tf.argmax(self._m_logits, axis=1)
    correct = tf.equal(self._m_prediction, tf.argmax(self._m_ph_label, axis=1))
    self._m_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))

with tf.name_scope("optimizer"):
    self._m_global_step = tf.Variable(0, name="global_step", trainable=False)
    self._m_optimizer = tf.train.AdamOptimizer(self._m_config["learning_rate"])
    self._m_train_op = self._m_optimizer.minimize(
                            self._m_loss, global_step=self._m_global_step)

孿生網(wǎng)絡(luò)是先建模再匹配坑资,LSTMa一直到h3(a)才只知道有h4(b),有沒有可能句子一開始就知道另外一條句子,并記性匹配了穆端? 下一節(jié) Match Pyramid是先匹配再建模袱贮。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市体啰,隨后出現(xiàn)的幾起案子攒巍,更是在濱河造成了極大的恐慌,老刑警劉巖荒勇,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件柒莉,死亡現(xiàn)場離奇詭異,居然都是意外死亡沽翔,警方通過查閱死者的電腦和手機兢孝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人西潘,你說我怎么就攤上這事卷玉。” “怎么了喷市?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵相种,是天一觀的道長。 經(jīng)常有香客問我品姓,道長寝并,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任腹备,我火速辦了婚禮衬潦,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘植酥。我一直安慰自己镀岛,他們只是感情好,可當我...
    茶點故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布友驮。 她就那樣靜靜地躺著漂羊,像睡著了一般。 火紅的嫁衣襯著肌膚如雪卸留。 梳的紋絲不亂的頭發(fā)上走越,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天,我揣著相機與錄音耻瑟,去河邊找鬼旨指。 笑死,一個胖子當著我的面吹牛喳整,可吹牛的內(nèi)容都是我干的谆构。 我是一名探鬼主播,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼算柳,長吁一口氣:“原來是場噩夢啊……” “哼低淡!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起瞬项,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤蔗蹋,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后囱淋,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體猪杭,經(jīng)...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年妥衣,在試婚紗的時候發(fā)現(xiàn)自己被綠了皂吮。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片戒傻。...
    茶點故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖蜂筹,靈堂內(nèi)的尸體忽然破棺而出丛塌,到底是詐尸還是另有隱情妒茬,我是刑警寧澤雪营,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布鸿染,位于F島的核電站,受9級特大地震影響麻裳,放射性物質(zhì)發(fā)生泄漏口蝠。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一津坑、第九天 我趴在偏房一處隱蔽的房頂上張望妙蔗。 院中可真熱鬧,春花似錦疆瑰、人聲如沸眉反。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽禁漓。三九已至跟衅,卻和暖如春孵睬,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背伶跷。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工掰读, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人叭莫。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓蹈集,卻偏偏與公主長得像,于是被迫代替她去往敵國和親雇初。 傳聞我的和親對象是個殘疾皇子拢肆,可洞房花燭夜當晚...
    茶點故事閱讀 45,047評論 2 355

推薦閱讀更多精彩內(nèi)容