TensorFlow2.0常用函数(三)

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

缘起性空、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值