常用函数
tf.data.Dataset.from_tensor_slices((输入特征, 标签))
切分传入张量的第一维度,生成输入特征/标签对,构建数据集,此函数对 Tensor 格式与 Numpy格式均适用,其切分的是第一维度,表征数据集中数据的数量,之后切分 batch等操作都以第一维为基础。例如:
featrure = tf.constant([12,23,10,17])
labels = tf.constant([0,1,1,0])
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
print(dataset)
for element in dataset:
printI(element)
运行结果:
<TensorSliceDataset shapes: ((),()), types: (tf.int32, tf.int32))> # (特征,标签)配对
(<tf.Tensor: id=9, shape=(), dtype=int32, numpy=12>, <tf.Tensor: id=10, shape=(),
dtype=int32, numpy=0>)
(<tf.Tensor: id=11, shape=(), dtype=int32, numpy=23>, <tf.Tensor: id=12, shape=(),
dtype=int32, numpy=1>)
(<tf.Tensor: id=13, shape=(), dtype=int32, numpy=10>, <tf.Tensor: id=14, shape=(),
dtype=int32, numpy=1>)
(<tf.Tensor: id=15, shape=(), dtype=int32, numpy=17>, <tf.Tensor: id=16, shape=(),
dtype=int32, numpy=0>)
tf.GradientTape()
with结构记录计算过程,gradient求出张量的梯度
with tf.GradientTape() as tape:
若干个计算过程
grad = tape.gradient(函数,对谁求导)
with tf.GradientTape( ) as tape:
w = tf.Variable(tf.constant(3.0))
loss = tf.pow(w,2) #loss=w2 loss’=2w
grad = tape.gradient(loss,w)
print(grad)
运行结果:
tf.Tensor(6.0, shape=(), dtype=float32)
enumerate(列表名)
enumerate是python的内建函数,它可遍历每个元素(如列表、元组或字符串), 组合为:索引 元素,常在for循环中使用。
seq = ['one','two','tfree']
for i, element in enumerate(seq):
print(i, element)
运行结果:
0 one
1 two
2 three
tf.one_hot(待转换数据,depth=几分类)
独热编码(one-hot encoding):在分类问题中,常用独热编码做标签,标记类别:1表示是,0表示非。
tf.one_hot()函数将待转换数据,转换为one-hot形式的数据输出。
例如:(0狗尾草鸢尾 1杂色鸢尾 2弗吉尼亚鸢尾)
标 签:1
独热码:(0 1 0)
classes = 3
labels = tf.constant([1,0,2]) # 输入的元素值最小为0,最大为2
output = tf.one_hot( labels, depth=classes )
print(output)
运行结果:
[[0. 1. 0.]
[1. 0. 0.]
[0. 0. 1.]], shape=(3, 3), dtype=float32)
tf.nn.softmax
当n分类的n个输出(y0 , y1, …… yn-1))通过softmax()函数,便符合概率分布了。
y = constant([1.01,2.01.-0.66])
y_pro = tf.nn.softmax(y)
print("After softmax,y_pro id :", y_pro)
运行结果:
After softmax, y_pro is: tf.Tensor([0.25598174 0.69583046
0.0481878], shape=(3,), dtype=float32)
assign_sub
赋值操作,更新参数的值并返回。
调用assign_sub前,先用 tf.Variable 定义变量 w 为可训练(可自更新)。
利用 assign_sub 对参数实现自更新。使用此函数前需利用 tf.Variable定义变量 w为可训练(可自更新),举例如下:
w = tf.Variable(4)
w.assign_sub(1) # w - = 1 即 w = w - 1
print(w)
运行结果:
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
tf.argmax
tf.argmax(张量名,axis=操作轴)
tf.argmax (张量名,axis=操作轴)返回张量沿指定维度最大值的索引,维度定义与之前讲的一致。举例如下:
import numpy as np
import tensorflow as tf
test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]])
print(test)
print(tf.argmax(test, axis=0)) # 返回每一列(经度)最大值的索引
print(tf.argmax(test, axis=1)) # 返回,每一行(纬度)最大值的索引
运行结果:
[[1 2 3]
[2 3 4]
[5 4 3]
[8 7 2]]
tf.Tensor([3 3 1], shape=(3,), dtype=int64)
tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)