DSSM & Multi-view DSSM TensorFlow实现

DSSM & Multi-view DSSM TensorFlow实现LearningDeepStructuredSemanticModelsforWebSearchusingClickthroughData以及其后续文章AMulti-ViewDeepLearningApproachforCrossDomainUserModelinginRecommendationSystems的实现Demo。1.数据D

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

Learning Deep Structured Semantic Models for Web Search using Clickthrough Data以及其后续文章

A Multi-View Deep Learning Approach for Cross Domain User Modeling in Recommendation Systems的实现Demo。

1. 数据

DSSM,对于输入数据是Query对,即Query短句和相应的展示,展示中分点击和未点击,分别为正负样,同时对于点击的先后顺序,也是有不同赋值,具体可参考论文。

对于我的Query数据本人无权开放,还请自行寻找数据。

2. word hashing

原文使用3-grams,对于中文,我使用了uni-gram,因为中文本身字有一定代表意义(也有论文拆笔画),对于每个gram都使用one-hot编码代替,最终可以大大降低短句维度。

3. 结构

结构图:

DSSM & Multi-view DSSM TensorFlow实现

  1. 把条目映射成低维向量。
  2. 计算查询和文档的cosine相似度。

3.1 输入

这里使用了TensorBoard可视化,所以定义了name_scope:

with tf.name_scope('input'):
    query_batch = tf.sparse_placeholder(tf.float32, shape=[None, TRIGRAM_D], name='QueryBatch')
    doc_positive_batch = tf.sparse_placeholder(tf.float32, shape=[None, TRIGRAM_D], name='DocBatch')
    doc_negative_batch = tf.sparse_placeholder(tf.float32, shape=[None, TRIGRAM_D], name='DocBatch')
    on_train = tf.placeholder(tf.bool)

Jetbrains全家桶1年46,售后保障稳定

3.2 全连接层

我使用三层的全连接层,对于每一层全连接层,除了神经元不一样,其他都一样,所以可以写一个函数复用。
l n = W n x + b 1 l_n = W_n x + b_1 ln=Wnx+b1

def add_layer(inputs, in_size, out_size, activation_function=None):
    wlimit = np.sqrt(6.0 / (in_size + out_size))
    Weights = tf.Variable(tf.random_uniform([in_size, out_size], -wlimit, wlimit))
    biases = tf.Variable(tf.random_uniform([out_size], -wlimit, wlimit))
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

其中,对于权重和Bias,使用了按照论文的特定的初始化方式:

	wlimit = np.sqrt(6.0 / (in_size + out_size))
    Weights = tf.Variable(tf.random_uniform([in_size, out_size], -wlimit, wlimit))
    biases = tf.Variable(tf.random_uniform([out_size], -wlimit, wlimit))

Batch Normalization

def batch_normalization(x, phase_train, out_size):
    """ Batch normalization on convolutional maps. Ref.: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow Args: x: Tensor, 4D BHWD input maps out_size: integer, depth of input maps phase_train: boolean tf.Varialbe, true indicates training phase scope: string, variable scope Return: normed: batch-normalized maps """
    with tf.variable_scope('bn'):
        beta = tf.Variable(tf.constant(0.0, shape=[out_size]),
                           name='beta', trainable=True)
        gamma = tf.Variable(tf.constant(1.0, shape=[out_size]),
                            name='gamma', trainable=True)
        batch_mean, batch_var = tf.nn.moments(x, [0], name='moments')
        ema = tf.train.ExponentialMovingAverage(decay=0.5)

        def mean_var_with_update():
            ema_apply_op = ema.apply([batch_mean, batch_var])
            with tf.control_dependencies([ema_apply_op]):
                return tf.identity(batch_mean), tf.identity(batch_var)

        mean, var = tf.cond(phase_train,
                            mean_var_with_update,
                            lambda: (ema.average(batch_mean), ema.average(batch_var)))
        normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3)
    return normed

单层

with tf.name_scope('FC1'):
    # 激活函数在BN之后,所以此处为None
    query_l1 = add_layer(query_batch, TRIGRAM_D, L1_N, activation_function=None)
    doc_positive_l1 = add_layer(doc_positive_batch, TRIGRAM_D, L1_N, activation_function=None)
    doc_negative_l1 = add_layer(doc_negative_batch, TRIGRAM_D, L1_N, activation_function=None)

with tf.name_scope('BN1'):
    query_l1 = batch_normalization(query_l1, on_train, L1_N)
    doc_l1 = batch_normalization(tf.concat([doc_positive_l1, doc_negative_l1], axis=0), on_train, L1_N)
    doc_positive_l1 = tf.slice(doc_l1, [0, 0], [query_BS, -1])
    doc_negative_l1 = tf.slice(doc_l1, [query_BS, 0], [-1, -1])
    query_l1_out = tf.nn.relu(query_l1)
    doc_positive_l1_out = tf.nn.relu(doc_positive_l1)
    doc_negative_l1_out = tf.nn.relu(doc_negative_l1)
······

合并负样本

with tf.name_scope('Merge_Negative_Doc'):
    # 合并负样本,tile可选择是否扩展负样本。
    doc_y = tf.tile(doc_positive_y, [1, 1])
    for i in range(NEG):
        for j in range(query_BS):
            # slice(input_, begin, size)切片API
            doc_y = tf.concat([doc_y, tf.slice(doc_negative_y, [j * NEG + i, 0], [1, -1])], 0)

3.3 计算cos相似度

with tf.name_scope('Cosine_Similarity'):
    # Cosine similarity
    # query_norm = sqrt(sum(each x^2))
    query_norm = tf.tile(tf.sqrt(tf.reduce_sum(tf.square(query_y), 1, True)), [NEG + 1, 1])
    # doc_norm = sqrt(sum(each x^2))
    doc_norm = tf.sqrt(tf.reduce_sum(tf.square(doc_y), 1, True))

    prod = tf.reduce_sum(tf.multiply(tf.tile(query_y, [NEG + 1, 1]), doc_y), 1, True)
    norm_prod = tf.multiply(query_norm, doc_norm)

    # cos_sim_raw = query * doc / (||query|| * ||doc||)
    cos_sim_raw = tf.truediv(prod, norm_prod)
    # gamma = 20
    cos_sim = tf.transpose(tf.reshape(tf.transpose(cos_sim_raw), [NEG + 1, query_BS])) * 20

3.4 定义损失函数

with tf.name_scope('Loss'):
    # Train Loss
    # 转化为softmax概率矩阵。
    prob = tf.nn.softmax(cos_sim)
    # 只取第一列,即正样本列概率。
    hit_prob = tf.slice(prob, [0, 0], [-1, 1])
    loss = -tf.reduce_sum(tf.log(hit_prob))
    tf.summary.scalar('loss', loss)

3.5选择优化方法

with tf.name_scope('Training'):
    # Optimizer
    train_step = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(loss)

3.6 开始训练

# 创建一个Saver对象,选择性保存变量或者模型。
saver = tf.train.Saver()
# with tf.Session(config=config) as sess:
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train', sess.graph)
    start = time.time()
    for step in range(FLAGS.max_steps):
        batch_id = step % FLAGS.epoch_steps
        sess.run(train_step, feed_dict=feed_dict(True, True, batch_id % FLAGS.pack_size, 0.5))

GitHub完整代码 https://github.com/InsaneLife/dssm

Multi-view DSSM实现同理,可以参考GitHub:multi_view_dssm

CSDN原文:http://blog.csdn.net/shine19930820/article/details/79042567

注意:
由于之前代码api过时,已更新最新代码于:https://github.com/InsaneLife/dssm/blob/master/dssm_rnn.py 数据处理代码data_input.py 和数据data 已经更新,由于使用了rnn,所以输入非bag of words方式。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/200895.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

  • Visual Studio 2010 旗舰版免序列号安装体验

    Visual Studio 2010 旗舰版免序列号安装体验VisualStudio2010E文版已经发布多时,由于工作原因没有及早的下载体验,直到前几天园子里的朋友放出了下载简体中文的种子ed2k://|file|cn_visual_studio_2010_ultimate_x86_dvd_532347.iso|2685982720|4AE6228933DDE49D9BFA4C3467C831C2|/于是决定下来体验一把,网速慢,2.5G下了2…

  • 什么是Promise,我们用它来做什么?[通俗易懂]

    什么是Promise,我们用它来做什么?[通俗易懂]一、什么是Promise?我们用Promise来解决什么问题?Promise是异步编程的一种解决方案:从语法上讲,promise是一个对象,从它可以获取异步操作的消息;从本意上讲,它是承诺,承诺它过一段时间会给你一个结果。promise有三种状态:pending(等待态),fulfiled(成功态),rejected(失败态);状态一旦改变,就不会再变。创造promise实例后,它会立即执行。我…

  • MD编辑器设置字体、颜色、大小

    MD编辑器设置字体、颜色、大小颜色:浅红色文字:浅红色文字:深红色文字:深红色文字浅绿色文字:浅绿色文字深绿色文字:深绿色文字浅蓝色文字:浅蓝色文字深蓝色文字:深蓝色文字浅黄色文字:浅黄色文字深黄色文字:深黄色文字浅青色文字:浅青色文字深青色文字:深青色文字浅紫色文字:浅紫色文字深紫色文字:深紫色文字大小:size为1:size为1size为2:size为2size为3:size为3size为4:size为4size为10:size为10字体:我是黑体字我是宋体字我是微软雅黑字我是fanta

  • linux下安装pycharm到桌面_Linux下载pycharm

    linux下安装pycharm到桌面_Linux下载pycharm工欲善其事,必先利其器。既然开始学习了,就得有好的工具嘛!这里lz选了个pycharm的编译工具。可能是看着比较舒服吧(其实就是感觉和idea一样),当时也想着用eclipse安装插件,后来也没有用。该干嘛的就是干嘛的,我可不想任务栏里一排排的eclipse。要是着急了,傻傻分不清。lz建议条件允许的话,就不要用激活成功教程版了,还是正版才是王道。社区版也能满足日常的一些开发。废话不多说,下来开始我们伟大…

  • python装饰器详解_python三层装饰器

    python装饰器详解_python三层装饰器装饰器装饰器放在一个函数开始定义的地方,它就像一顶帽子一样戴在这个函数的头上。和这个函数绑定在一起。在我们调用这个函数的时候,第一件事并不是执行这个函数,而是将这个函数做为参数传入它头顶上这顶帽子,

  • html导航栏可以展开的下拉菜单,html导航栏下拉菜单如何制作[通俗易懂]

    html导航栏可以展开的下拉菜单,html导航栏下拉菜单如何制作[通俗易懂]html导航栏下拉菜单如何制作发布时间:2020-09-2615:29:13来源:亿速云阅读:88作者:小新小编给大家分享一下html导航栏下拉菜单如何制作,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!我们要说的是html导航栏下拉菜单的制作,先看一个完整的实例代码:.dropdown{position:relative;display:inline-block;}.drop…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号