在编写RNN程序时,一个很常见的函数就是sequence_loss_by_example

loss = tf.contrib.legacy_seq2seq.sequence_loss_by_example(logits_list, targets_list, weights_list, average_across_timesteps)

这个函数在contrib中的legacy(遗产)中,可见这个函数不是tensorflow支持的官方函数。

import numpy as np
import tensorflow as tf 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, logits) -> loss-batch
to be used instead of the standard softmax (the default if this is None).
**Note that to avoid confusion, it is required for the function to accept
named arguments.**
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 tf.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:
# 默认使用sparse
target = tf.reshape(target, [-1])
crossent = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=target, logits=logit)
else:
crossent = softmax_loss_function(labels=target, logits=logit)
log_perp_list.append(crossent * weight)
# 把各个时间片的损失加起来
log_perps = tf.add_n(log_perp_list)
# 对各个时间片的损失求平均数
if average_across_timesteps:
total_size = tf.add_n(weights)
total_size += 1e-12 # Just to avoid division by 0 for all-0 weights.
log_perps /= total_size
return log_perps """
考虑many2many形式的RNN用法,每次输入一个就会得到一个输出
这些输出需要计算平均损失,我们可以指定:
* 每个样本的权重
* 每个时间片的权重
"""
sample_count = 4
target_count = 3
frame_count = 2
# 各个时间片我的答案
logits = [tf.random_uniform((sample_count, target_count)) for i in range(frame_count)]
# 各个时间片的真正答案
targets = [tf.constant(np.random.randint(0, target_count, (sample_count,))) for i in range(frame_count)]
# 每个时间片,每个样本的权重。利用weights我们可以指定时间片权重和样本权重
weights = [tf.ones((sample_count,), dtype=tf.float32) * (i + 1) for i in range(frame_count)]
loss1 = sequence_loss_by_example(logits, targets, weights, average_across_timesteps=True)
loss = tf.contrib.legacy_seq2seq.sequence_loss_by_example(logits, targets, weights, True)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
x, y, = sess.run([loss, loss1])
print(x)
print(y)
print(x.shape, y.shape)

这个函数非常有用,tensorflow.nn中的sparse_softmax_cross_entropy无法指定样本的权重,这个函数可以。

使用时,只需要传入一个时间片即可。如果各个样本权重都为1,最后得到的结果跟sparse_softmax_cross_entropy得到的结果是一样的。

tensorflow中的sequence_loss_by_example的更多相关文章

  1. 在TensorFlow中基于lstm构建分词系统笔记

    在TensorFlow中基于lstm构建分词系统笔记(一) https://www.jianshu.com/p/ccb805b9f014 前言 我打算基于lstm构建一个分词系统,通过这个例子来学习下 ...

  2. Tensorflow中的padding操作

    转载请注明出处:http://www.cnblogs.com/willnote/p/6746668.html 图示说明 用一个3x3的网格在一个28x28的图像上做切片并移动 移动到边缘上的时候,如果 ...

  3. CNN中的卷积核及TensorFlow中卷积的各种实现

    声明: 1. 我和每一个应该看这篇博文的人一样,都是初学者,都是小菜鸟,我发布博文只是希望加深学习印象并与大家讨论. 2. 我不确定的地方用了"应该"二字 首先,通俗说一下,CNN ...

  4. python/numpy/tensorflow中,对矩阵行列操作,下标是怎么回事儿?

    Python中的list/tuple,numpy中的ndarrray与tensorflow中的tensor. 用python中list/tuple理解,仅仅是从内存角度理解一个序列数据,而非数学中标量 ...

  5. [翻译] Tensorflow中name scope和variable scope的区别是什么

    翻译自:https://stackoverflow.com/questions/35919020/whats-the-difference-of-name-scope-and-a-variable-s ...

  6. SSD:TensorFlow中的单次多重检测器

    SSD:TensorFlow中的单次多重检测器 SSD Notebook 包含 SSD TensorFlow 的最小示例. 很快,就检测出了两个主要步骤:在图像上运行SSD网络,并使用通用算法(top ...

  7. 在 TensorFlow 中实现文本分类的卷积神经网络

    在TensorFlow中实现文本分类的卷积神经网络 Github提供了完整的代码: https://github.com/dennybritz/cnn-text-classification-tf 在 ...

  8. [开发技巧]·TensorFlow中numpy与tensor数据相互转化

    [开发技巧]·TensorFlow中numpy与tensor数据相互转化 个人主页–> https://xiaosongshine.github.io/ - 问题描述 在我们使用TensorFl ...

  9. TensorFlow中的变量和常量

    1.TensorFlow中的变量和常量介绍 TensorFlow中的变量: import tensorflow as tf state = tf.Variable(0,name='counter') ...

随机推荐

  1. Laravel学习笔记之Session源码解析(上)

    说明:本文主要通过学习Laravel的session源码学习Laravel是如何设计session的,将自己的学习心得分享出来,希望对别人有所帮助.Laravel在web middleware中定义了 ...

  2. 使用新版SDK不想跳转微博客户端能否直接发送微博分享?

    如题啊如题! 新版本中没有StatusesAPI?????

  3. 文本分类需要CNN?No!fastText完美解决你的需求(后篇)

    http://blog.csdn.net/weixin_36604953/article/details/78324834 想必通过前一篇的介绍,各位小主已经对word2vec以及CBOW和Skip- ...

  4. 斯坦福深度学习与nlp第四讲词窗口分类和神经网络

    http://www.52nlp.cn/%E6%96%AF%E5%9D%A6%E7%A6%8F%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E4%B8%8Enlp%E7%A ...

  5. ES8新特性——ES8 was Released and here are its Main New Features

    原文: https://hackernoon.com/es8-was-released-and-here-are-its-main-new-features-ee9c394adf66 -------- ...

  6. Java-Shiro(三):Shiro与Spring MVC集成

    新建Java Daynamic Web项目 导入Spring.SpringMVC依赖包: 导入Spring & Spring MVC包(导入如下所有开发包): Spring AOP依赖扩展包: ...

  7. jquery animate()背景色渐变的处理

    jquery animate函数不能处理背景色渐变,需要使用jquery.color插件 gitHub地址:https://github.com/jquery/jquery-color/ 使用代码: ...

  8. JavaScript 闭包(个人理解)

    当function里嵌套function时,内部的function可以访问外部function里的变量.但这不是闭包 function foo(x) { var tmp = 3; function b ...

  9. OpenGL ES 3.0之Texturing纹理详解(二)

    Texture Filtering and Mipmapping 纹理过滤与多级纹理 前面我们已经讲了单个2D图像的2D纹理的介绍,这篇文章主要讲解多级纹理.纹理坐标是用于生成一个2D索引,当放大和缩 ...

  10. Android Studio “懒人”必备插件android layout id converter

    在一个布局文件里.假设定义了非常多非常多id,代码中一个个findview是一件非常枯燥而且浪费时间的事情. 所以这里向大家推荐一个必备插件android layout id converter. 配 ...