1、tf.data.Dataset.from_tensor_slices((特征数据,标签)) #切分tensor的第一维度,生成输入特征/标签对,构建数据集
import tensorflow as tf
features = tf.constant([11,23,33,14,52,16],dtype=tf.int32);
lables = tf.constant([0,1,0,1,0,1],dtype=tf.int32)
labelPair = tf.data.Dataset.from_tensor_slices((features,lables))
print(labelPair)
for labelPairItem in labelPair:
print(labelPairItem)
输出结果:
<_TensorSliceDataset element_spec=(TensorSpec(shape=(), dtype=tf.int32, name=None), TensorSpec(shape=(), dtype=tf.int32, name=None))>
(<tf.Tensor: shape=(), dtype=int32, numpy=11>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=33>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=14>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=52>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=16>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
2、tf.GardientTape() #张量梯度计算函数,以下代码示例是GardientTape函数的使用方法,实现了损失函数loss对参数w的求导计算,w初始化必须是训练变量
import tensorflow as tf
with tf.GradientTape() as tape:
w=tf.Variable(tf.constant(3.0), trainable=True)
loss = tf.pow(w,2)
grad = tape.gradient(loss,w)
print(grad)
输出结果:
tf.Tensor(6.0, shape=(), dtype=float32)
3、enumberate(列表) #这个是python的内建函数,可遍历每个元素(列表、元祖、字符串),组合为:索引 元素
import tensorflow as tf
listData= ['c','python','java']
for i,element in enumerate(listData):
print(i,element)
输出结果:
0 c
1 python
2 java
4、tf.one_hot() #可以将类别索引转换为onehot编码,onehot编码是一种代表分类变量的编码方式。在onehot编码中,对于N个分类,我们用一个长度为N的向量来表示某个类别,其中除了对应该分类的索引位置为1,其余位置为0
import tensorflow as tf
lables = [1, 2, 3]
depth = 3
one_hot = tf.one_hot(lables, depth)
print(one_hot)
输出结果:(输出结果为一个3x3的Tensor,表示3个样本的onehot编码)
tf.Tensor(
[[0. 1. 0.]
[0. 0. 1.]
[0. 0. 0.]], shape=(3, 3), dtype=float32)