写在前面,不算一篇公开的博客,只是记录自己在阅读代码时碰到的函数,随手百度随手记录。
此外,在科研中遇到的tf或者pytorch中的不知道功能的函数,都可以在python console中查看相关文档。
首先是 import tensorflow。dir()函数帮助查看tensorflow下面的子文件(函数)
然后是运用help()函数,注意在查看tf中的方法时,不需要加括号进去
1. tf.one_hot函数
one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)
Returns a one-hot tensor
用于将indices转换成one-hot类型的数据,depth为one-hot向量的长度。
a = [1, 2, 3]
tensorflow.one_hot(a, 3) # depth为3
output:
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.]], dtype=float32)>
2. tf.sparse.SparseTensor类
SparseTensor(indices, values, dense_shape)
indices:表示稀疏矩阵的非零值元素的索引值,是二维的
values:表示稀疏矩阵中非零元素,与indices一一对应,是一维的
dense_shape:表示稀疏矩阵的维度
3. tf.reduce_sum函数
表示的是求和函数,可以通过调整 axis =0,1 的维度来控制求和维度
reduce_sum(input_tensor, axis=None, keepdims=False, name=None)
4. tf.math.unsorted_segment_sum
先附上官方定义
但是看了网上一些讲解和例子,还是没能搞懂,于是就debug去代码里面看了一下,懂了。
假设我们现在又三个二分类问题分别是0/ 1/ 2,将问题按照[0, 1, 2, 0, 1]的顺序分发给工人,我们收到的data为 [0, 1, 0, 1, 1] ,最后我们怎么收集这些问题的票数?(个人认为例子已经很详尽了,不再多加说明)
import tensorflow as tf
import numpy as mp
data = [0, 1, 0, 1, 1]
# 将其转换成one-hot向量
data = tf.one_hot(data, depth=2)
"""
<tf.Tensor: shape=(5, 2), dtype=float32, numpy=
array([[1., 0.],
[0., 1.],
[1., 0.],
[0., 1.],
[0., 1.]], dtype=float32)>
"""
object_index = [0, 1, 2, 0, 1] # 问题列表
data_process = tf.math.unsorted_segment_sum(data, object_index, 3) # 3为问题种类数
"""
最终的输出结果
<tf.Tensor: shape=(5, 2), dtype=float32, numpy=
array([[1., 1.],
[0., 2.],
[1., 0.]], dtype=float32)>
"""