文本生成相关笔记
tf.function
1、从生成的概率向量里随即采样
tf.random.categorical(
logits, num_samples, dtype=None, seed=None, name=None
)
# samples has shape [1, 5], where each value is either 0 or 1 with equal
# probability.
samples = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5)
##详细参考链接:https://blog.csdn.net/menghuanshen/article/details/105356239
损失函数相关
1、SparseCategoricalCrossentropy与CategoricalCrossentropy
##需求:输出为一个概率向量,但是label是一个标量,此时怎么计算loss呢?使用SparseCategoricalCrossentropy解决
tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=False, reduction=losses_utils.ReductionV2.AUTO,
name='sparse_categorical_crossentropy'
)
from_logits=False,##output为经过softmax输出的概率值。
from_logits=True,##output为经过网络直接输出的 logits张量。
##在深度学习之中logits就是输入到softmax之前的数值,本质上反映的也是概率,softmax只是归一化一下。
#logits解释可参考链接: https://www.zhihu.com/question/60751553
##注意: If you want to provide labels using one-hot representation,please use CategoricalCrossentropy loss.
## 示例
y_true = [1, 2]
y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
# Using 'auto'/'sum_over_batch_size' reduction type.
scce = tf.keras.losses.SparseCategoricalCrossentropy()
scce(y_true, y_pred).numpy()