tf loss构建常用到函数

1、tf.map_fn

tf.map_fn是TensorFlow中的一个函数,用于对给定的函数和输入进行逐元素的映射,其定义如下:

python 复制代码
tf.map_fn(
    fn,
    elems,
    dtype=None,
    parallel_iterations=None,
    back_prop=True,
    swap_memory=False,
    infer_shape=True,
    name=None,
    fn_output_signature=None
)

tf1.x中tf.map_fn没有fn_output_signature参数

tf.map_fn案例

python 复制代码
tf.map_fn(fn=lambda t: tf.range(t, t + 3), elems=tf.constant([3, 5, 2]))

https://www.tensorflow.org/api_docs/python/tf/map_fn

tf.map_fn( )的用法-CSDN博客

bash 复制代码
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[3, 4, 5],
       [5, 6, 7],
       [2, 3, 4]], dtype=int32)>

2、tf.pad

定义 :tf.pad()函数是TensorFlow中的一个方法,用于在张量的边界上进行填充。

复制代码
tf.pad(tensor, paddings, mode='CONSTANT', constant_values=0)

参数解释:

  • tensor:需要填充的张量。
  • paddings:填充的大小,格式为[[pad_top, pad_bottom], [pad_left, pad_right], ...],其中每个维度的填充大小为两个元素的列表。例如,如果填充第一个维度10个元素,则paddings为[[10, 0], [0, 0]]。
  • mode:填充模式。可选值有'CONSTANT'、'REFLECT'、'SYMMETRIC'。默认为'CONSTANT',表示使用常数进行填充。
  • constant_values:当mode为'CONSTANT'时,用于填充的常数值,默认为0。

返回值: 返回填充后的张量。

案例:

python 复制代码
import tensorflow as tf

# 创建一个输入张量
x = tf.constant([[1, 2], [3, 4]])

# 使用tf.pad函数在各个维度上进行填充
result = tf.pad(x, paddings=[[1, 1], [2, 2]])

print(result)

paddings=[[1, 1], [2, 2]]是指在第1维的上下均填充1维,在第2维的左右都填充2维

输出结果

bash 复制代码
<tf.Tensor: shape=(4, 6), dtype=int32, numpy=
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 1, 2, 0, 0],
       [0, 0, 3, 4, 0, 0],
       [0, 0, 0, 0, 0, 0]], dtype=int32)>

https://www.tensorflow.org/api_docs/python/tf/pad

3、tf.where

python 复制代码
tf.where(
    condition, x=None, y=None, name=None
)

tf.where是一个用于根据条件选择元素的函数。它的作用类似于Python中的条件表达式(ternary expression)。

tf.where函数接受一个条件张量和两个张量(或者相同形状的数组)作为输入,并返回一个新的张量,其中根据条件选择了对应位置的元素。

以下是一个示例,演示如何使用tf.where函数选择满足条件的元素:

python 复制代码
import tensorflow as tf

# 创建一个条件张量和两个输入张量
condition = tf.constant([True, False, True])
x = tf.constant([1, 2, 3])
y = tf.constant([4, 5, 6])

# 使用tf.where根据条件选择元素
result = tf.where(condition, x, y)

print(result)

输出结果

python 复制代码
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 5, 3], dtype=int32)>

4、tf.expand_dims

定义

python 复制代码
tf.expand_dims(
    input, axis, name=None
)

tf.expand_dims是TensorFlow中的一个函数,用于在张量的特定维度上插入新的维度。

tf.expand_dims函数接受一个输入张量和一个axis参数,它在输入张量的axis位置插入一个新的维度。

以下是一个示例,展示如何使用tf.expand_dims函数在张量的特定维度上插入新的维度:

python 复制代码
import tensorflow as tf

# 创建一个输入张量
x = tf.constant([1, 2, 3, 4])

# 在维度1上插入新的维度
result = tf.expand_dims(x, axis=1)

print(result)

在这个示例中,我们首先创建了一个输入张量x,其中包含了四个元素。然后,我们使用tf.expand_dims函数在维度1上插入新的维度。最后,打印结果。

python 复制代码
tf.Tensor(
[[1]
 [2]
 [3]
 [4]], shape=(4, 1), dtype=int32)

5、tf.tile

定义

python 复制代码
tf.tile(
    input: _atypes.TensorFuzzingAnnotation[TV_Tile_T],
    multiples: _atypes.TensorFuzzingAnnotation[TV_Tile_Tmultiples],
    name=None
) -> _atypes.TensorFuzzingAnnotation[TV_Tile_T]

tf.tile是TensorFlow中的一个函数,用于在给定维度上复制张量的值。

tf.tile函数接受一个输入张量和一个multiples参数,它在输入张量的每个维度上复制相应倍数的值,并返回一个新的张量。

以下是一个示例,演示如何使用tf.tile函数在给定维度上复制张量的值

python 复制代码
import tensorflow as tf

# 创建一个输入张量
x = tf.constant([1, 2, 3])

# 在维度0上复制2次
result = tf.tile(x, multiples=[2])

print(result)

输出结果:

复制代码
tf.Tensor([1 2 3 1 2 3], shape=(6,), dtype=int32)

可以看到,通过tf.tile函数在维度0上复制了两次输入张量的值,得到了一个形状为(6,)的新张量。

需要注意的是,multiples参数是一个列表,表示在每个维度上复制的倍数。如果multiples的长度小于输入张量的维度数,则会自动在后续维度上复制一次。例如,如果输入张量的形状是(3, 4, 5, 6),而multiples[2, 3],则会在维度0上复制2次,在维度1上复制3次,在维度2和维度3上各复制1次。

tf.tile函数在很多情况下非常有用,特别是在需要进行张量形状扩展或对齐操作时。

6、tf.gather_nd

tf.gather_nd是TensorFlow中的一个函数,用于根据索引获取多维张量中的元素的值。定义

python 复制代码
tf.gather_nd(
    params, indices, batch_dims=0, name=None
)

tf.gather_nd函数接受一个输入张量和一个索引张量作为输入,它根据索引张量中指定的索引位置,从输入张量中获取对应的元素值,并返回一个新的张量。

以下是一个示例,演示如何使用tf.gather_nd函数获取多维张量中的元素值:

python 复制代码
import tensorflow as tf

# 创建一个输入张量
x = tf.constant([[1, 2], [3, 4], [5, 6]])

# 创建一个索引张量
indices = tf.constant([[0, 0], [2, 1]])

# 使用tf.gather_nd函数获取元素值
result = tf.gather_nd(x, indices)

print(result)

在这个示例中,我们首先创建了一个输入张量x,它是一个 3x2 的张量。然后,我们创建了一个索引张量indices,其中包含了两个索引位置的坐标。接下来,我们使用tf.gather_nd函数根据索引张量获取输入张量中对应位置的元素值。最后,打印结果。

复制代码
tf.Tensor([1 6], shape=(2,), dtype=int32)

7、tf.reduce_min

tf.reduce_min是TensorFlow中的一个函数,用于计算张量在指定维度上的最小值。当在tf.reduce_min函数中不指定axis参数时,它会计算整个张量的最小值。定义

python 复制代码
output = tf.reduce_min(input_tensor, axis=None, keepdims=False, name=None)

案例

不指定axis时,计算整个张量的最小值

python 复制代码
import tensorflow as tf

# 创建一个输入张量
x = tf.constant([[1, 2, 3], [4, 5, 6]])

# 计算整个张量的最小值
result = tf.reduce_min(x)

print(result)

输出如下:

复制代码
tf.Tensor(1, shape=(), dtype=int32)

指定aixs时,计算aixs的维度的最小值

python 复制代码
import tensorflow as tf

# 创建一个输入张量
x = tf.constant([[1, 2], [3, 4]])

# 计算张量在维度0上的最小值
result = tf.reduce_min(x, axis=0)

print(result)

输出:

python 复制代码
tf.Tensor([1 2], shape=(2,), dtype=int32)

8、tf.stack

tf.stack将一系列 R 阶张量堆叠到一个 (R+1) 阶张量中。 定义

python 复制代码
tf.stack(
    values, axis=0, name='stack'
)
复制代码
通过沿轴维度将值中的张量列表打包为比每个张量高一级的张量。给定长度为 N 的形状为 (A, B, C) 的张量列表;如果 axis == 0 那么输出张量将具有形状 (N, A, B, C)。如果 axis == 1 那么输出张量将具有形状 (A, N, B, C)。

案例

python 复制代码
x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
tf.stack([x, y, z])

tf.stack([x, y, z], axis=1)
bash 复制代码
tf.stack([x,y,z])的输出
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 4],
       [2, 5],
       [3, 6]], dtype=int32)>


tf.stack([x,y,z],axis=1)的输出
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
       [4, 5, 6]], dtype=int32)>

9、tf.concat

tf.concat 是 TensorFlow 中的一个函数,用于沿指定的轴拼接张量。它接受一个张量列表,并沿着指定的轴拼接它们。定义

python 复制代码
tf.concat(
    values, axis, name='concat'
)

案例

python 复制代码
import tensorflow as tf

# 创建两个张量
tensor1 = tf.constant([[1, 2, 3], [4, 5, 6]])
tensor2 = tf.constant([[7, 8, 9], [10, 11, 12]])

# 沿轴0拼接
result = tf.concat([tensor1, tensor2], axis=0)

with tf.Session() as sess:
    print(sess.run(result))

结果输出

bash 复制代码
<tf.Tensor: shape=(4, 3), dtype=int32, numpy=
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]], dtype=int32)>

10、tensor.get_shape().as_list()

tensor.get_shape()获取tensor的维度,.as_list()以list的形式返回

python 复制代码
x = tf.constant([[1, 2, 3], [4, 5, 6]])
shape = x.get_shape().as_list()

输出

bash 复制代码
[2, 3]

11、tf.unique_with_counts

tf.unique_with_counts 函数用于对输入张量中的元素进行去重,并返回去重后的元素、元素在原始张量中的索引、元素在原始张量中的计数。x为1-d tensor,定义:

python 复制代码
y, idx, count = tf.unique_with_counts(x, out_idx=tf.int64)

https://github.com/tensorflow/docs/blob/r1.12/site/en/api_docs/python/tf/unique_with_counts.md

案例:

python 复制代码
x = tf.constant([1, 2, 3, 1, 2, 1, 3, 3, 3])
y, idx, count = tf.unique_with_counts(x)

输出结果

不重复的元素y:<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 2, 3], dtype=int32)>

索引下标idx:<tf.Tensor: shape=(9,), dtype=int32, numpy=array([0, 1, 2, 0, 1, 0, 2, 2, 2],dtype=int32)>

不重复元素对应的计数count: <tf.Tensor: shape=(3,), dtype=int32, numpy=array([3, 2, 4], dtype=int32)>

12、tf.greater_equal

tf.greater_equal 是 TensorFlow 中用于比较两个张量元素是否满足大于等于的元素级别比较的函数。定义如下:

python 复制代码
result = tf.greater_equal(x, y, name=None)

案例:

两个张量比较大小

python 复制代码
# 创建输入张量
x = tf.constant([1, 2, 3, 4])
y = tf.constant([2, 2, 2, 2])

# 进行元素级别的大于等于比较
result = tf.greater_equal(x, y)

输出:

bash 复制代码
<tf.Tensor: shape=(4,), dtype=bool, numpy=array([False,  True,  True,  True])>

张量和一个数值比较大小

python 复制代码
# 创建输入张量
x = tf.constant([1, 2, 3, 4])
y = 2

# 进行元素级别的大于等于比较
result = tf.greater_equal(x, y)

输出

bash 复制代码
<tf.Tensor: shape=(4,), dtype=bool, numpy=array([False,  True,  True,  True])>

13、tf.reshape

tf.reshape 是 TensorFlow 中用于改变张量形状的函数。它可以用来重新排列张量的维度,以适应不同的计算需求。

python 复制代码
reshaped_tensor = tf.reshape(tensor, shape, name=None)

案例

python 复制代码
x = tf.constant([[1, 2, 3], [4, 5, 6]])

# 改变张量形状
reshaped_x = tf.reshape(x, [3, 2])

输出结果

bash 复制代码
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 2],
       [3, 4],
       [5, 6]], dtype=int32)>

14、tf.cast

将一个 tensor 变为新的类型 type。定义

python 复制代码
tf.cast(
    x, dtype, name=None
)

案例

python 复制代码
x = tf.constant([1.8, 2.2], dtype=tf.float32)
tf.cast(x, tf.int32)

输出

bash 复制代码
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 2], dtype=int32)>

15、tf.div_no_nan

计算不安全除法,如果y等于0,则返回0。定义:

python 复制代码
tf.div_no_nan(
    x,
    y,
    name=None
)

案例:

python 复制代码
x = tf.constant([1, 2, 3, 4], dtype=tf.float32)
y = tf.constant([0, 2, 0, 4], dtype=tf.float32)
z=tf.div_no_nan(x,y)

输出:

bash 复制代码
<tf.Tensor: shape=(4,), dtype=float32, numpy=array([0., 1., 0., 1.], dtype=float32)>

16、tf.nn.softmax_cross_entropy_with_logits_v2

计算labels和logits之间的交叉熵,定义如下:

python 复制代码
tf.nn.softmax_cross_entropy_with_logits_v2(
    _sentinel=None,
    labels=None,
    logits=None,
    dim=-1,
    name=None
)

https://github.com/tensorflow/docs/blob/r1.12/site/en/api_docs/python/tf/nn/softmax_cross_entropy_with_logits_v2.md

案例

python 复制代码
import tensorflow as tf

# 创建标签张量和预测得分张量
labels = tf.constant([[0, 1, 0], [1, 0, 0]], dtype=tf.float32)
logits = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32)

# 计算 softmax 交叉熵损失
loss = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)

输出

bash 复制代码
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.4076059, 2.407606 ], dtype=float32)>

17、tf.math.log1p

tf.math.log1p 是 TensorFlow 中的一个数学函数,用于计算输入张量加1后的自然对数。

tf.math.log1p 的基本用法如下:

python 复制代码
output = tf.math.log1p(input)

案例

python 复制代码
x = tf.constant([1, 2, 3],dtype=tf.float32)
output = tf.math.log1p(x)

输出

python 复制代码
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([0.6931472, 1.0986123, 1.3862944], dtype=float32)>

参考文献

https://www.tensorflow.org/api_docs/python/tf/map_fn

tf.map_fn( )的用法-CSDN博客

tensorflow tf.pad解析_tensorflow.pad-CSDN博客

相关推荐
jumu2021 天前
高比例清洁能源接入下计及需求响应的配电网重构 关键词:高比例清洁能源;需求响应;配电网重构
tensorflow
serve the people2 天前
TensorFlow 2.0 手写数字分类教程
人工智能·分类·tensorflow
serve the people2 天前
tensorflow 深度解析 Sequential 模型的输入形状指定
人工智能·python·tensorflow
強云2 天前
win10安装在anaconda 中tensorflow2.10
tensorflow
serve the people3 天前
tensorflow Keras Sequential 模型
人工智能·tensorflow·keras
laocooon5238578864 天前
TensorFlow与 PyTorch有什么关联么
人工智能·pytorch·tensorflow
serve the people4 天前
tensorflow 深度解析 Sequential 模型的创建与层管理
人工智能·python·tensorflow
serve the people4 天前
tensorflow 零基础吃透:创建 tf.sparse.SparseTensor 的核心方法
人工智能·python·tensorflow
serve the people4 天前
tensorflow 零基础吃透:tf.sparse.SparseTensor 与核心 TensorFlow API 的协同使用
人工智能·python·tensorflow
serve the people4 天前
tensorflow 零基础吃透:TensorFlow 张量切片与数据插入(附目标检测 / NLP 实战场景)
目标检测·自然语言处理·tensorflow