Tensorflow1.x
tf.keras
Model
load_weights
# 从TensorFlow或HDF5文件加载所有层权重。
load_weights(
filepath, by_name=False
)
summary
# 打印网络的字符串摘要
summary(
line_length=None, positions=None, print_fn=None
)
fit_generator
fit_generator(
generator, # 生成器函数,输出应该是形为(inputs,target)或者(inputs,targets,sample_weight)的元组,
# 生成器会在数据集上无限循环
steps_per_epoch=None,# 在宣布一个epoch完成并开始下一个epoch之前从生成器产生的总步数(样本批次)。
#它通常应等于数据集的样本数除以batch_size。
epochs=1,#
verbose=1,
callbacks=None,# List of callbacks to be called during training.callbacks类的函数
validation_data=None,# 验证集数据
validation_steps=None,#
validation_freq=1,# 多少个epoch验证一次
class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False,
shuffle=True,# 没多少个epoch运行一次验证
initial_epoch=0# 开始训练的时期(用于恢复之前的训练)
)
tf.keras.callbacks
Callbacks: utilities called at certain points during model training.在训练模型的过程中可能要做一些事。
ModelCheckpoint
# Save the model after every epoch.
tf.keras.callbacks.ModelCheckpoint(
filepath, monitor='val_loss',# 需要监视的值,通常为:val_acc或val_loss或acc或 loss
verbose=0,# 信息展示模式,0或1。为1表示输出epoch模型保存信息,默认为0表示不输出该信息
# 信息形如:Epoch 00001: val_acc improved from -inf to 0.49240, saving model to
# /xxx/checkpoint/model_001-0.3902.h5
save_best_only=False,# 当设置为True时,将只保存在验证集上性能最好的模型
save_weights_only=False,#如果为True,只保存weights,否则保存整个模型
mode='auto',# 在save_best_only=True时决定性能最佳模型的评判准则
# 例如,当监测值为val_acc时,模式应为max,当检测值为val_loss时,模式应为min。
# 在auto模式下,评价准则由被监测值的名字自动推断。
save_freq='epoch',
**kwargs
)
Tensorflow2.x
https://github.com/aymericdamien/TensorFlow-Examples
https://github.com/instillai/TensorFlow-Course
https://github.com/sjchoi86/Tensorflow-101
https://github.com/terryum/TensorFlow_Exercises
keras是对tensorflow的再封装,是tensorflow的高级api
基本知识
*表示点乘 矩阵乘tf.matmul
tf.reduce_sum这个博客太强了,把axis彻彻底底讲明白了
本来维度是(2,3) axis=0 完事就变成了(3) 如果keepdims=True,就变成了(1,3)
如果axis是一个元组(1,2,3),就是先加维度1,加完加2,然后加3,如果没有传axis,默认所有的加起来
基本函数
tf.cast(x,dtype)
#张量数据类型转换
#x:要转换的数据
#dtype:目标数据类型
tf.shape(input,name=None,out_type=tf.int32)
#将矩阵的维度输出为一个维度矩阵
#input:张量
#name:op的名字,用于tensorboard中
#out_type:输出类型
tf.pad(tensor, paddings, mode='CONSTANT', constant_values=0, name=None)
#对张量在各个维度进行填充
#tensor:待填充的张量
#paddings:对哪个维度进行填充,上下左右填充多少,例如[[1,2],[3,4]],上填充一行,下2行,左3列,右4列
#mode 填充方式,有’CONSTANT’'REFLECT''SYMMETRIC'
#constant_values:constant填充值
#name:操作的名字
dataset.map(function)
#对dataset中的每一个tf.Tensor执行该函数操作
tf.fill(dims,value)
#创建一个充满标量值的张量。
tf.squeeze(tensor)
#把所有是1的维度都去除,捏一下,挤压一下,把水分挤出来
维度
tensorflow的维度情况是NHWC
架构
tf的API是不同的Module
嵌套,Module
里包括Class
和Function
,Class
包括Arguments
参数介绍,Attributes
属性,Methods
方法
tf.data.Dataset
- 从输入数据创建源数据集。
- 应用数据集转换对数据进行预处理。
- 遍历数据集并处理元素。
Source Datasets:
从列表:
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
for element in dataset:
print(element)
#tf.Tensor(1, shape=(), dtype=int32)
#tf.Tensor(2, shape=(), dtype=int32)
#tf.Tensor(3, shape=(), dtype=int32)
as_numpy_iterator
返回一个迭代器,它将数据集的所有元素转换为numpy。
使用as_numpy_iterator检查数据集的内容。要查看元素的形状和类型,请直接打印数据集元素,而不是使用as_numpy_iterator
batch
batch(
batch_size, drop_remainder=False
)
将连续数据组合为batch,drop_remainder表示如果最后的数据不够一批,是否删除
组合完的数据会多一个额外的维度batch_size,如下:
dataset = tf.data.Dataset.range(8)
dataset = dataset.batch(3)
for element in dataset:
print(element)
#tf.Tensor([0 1 2], shape=(3,), dtype=int64)
#tf.Tensor([3 4 5], shape=(3,), dtype=int64)
#tf.Tensor([6 7], shape=(2,), dtype=int64)
padded_batch
padded_batch(
batch_size, padded_shapes=None, padding_values=None, drop_remainder=False
)
也是生成batch的,不同的是如果有变长如何填充:
# Components of nested elements can be padded independently.
elements = [([1, 2, 3], [10]),
([4, 5], [11, 12])]
dataset = tf.data.Dataset.from_generator(
lambda: iter(elements), (tf.int32, tf.int32))
# Pad the first component of the tuple to length 4, and the second
# component to the smallest size that fits.
dataset = dataset.padded_batch(2,
padded_shapes=([4], [None]),
padding_values=(-1, 100))
list(dataset.as_numpy_iterator())
#[(array([[ 1, 2, 3, -1],
# [ 4, 5, -1, -1]], dtype=int32),
# array([[ 10, 100],
# [ 11, 12]], dtype=int32))]
map
Maps map_func
across the elements of this dataset.
prefetch(buffer_size)
这允许在处理当前元素时准备后面的元素。这通常会提高延迟和吞吐量,但代价是使用额外的内存来存储预先获取的元素。
cache
shuffle
随机打乱此数据集的元素。
这个数据集用buffer_size元素填充一个缓冲区,然后从这个缓冲区随机抽取元素,用新元素替换选中的元素。为了实现完美的洗牌,需要一个大于或等于数据集的完整大小的缓冲区。
例如,如果数据集包含10,000个元素,但buffer_size被设置为1,000,那么shuffle最初将从缓冲区中的前1,000个元素中随机选择一个元素。一旦一个元素被选中,它在缓冲区中的空间将被下一个元素(即1001 -st)替换,保持缓冲区的1,000个元素。
prefetch
流水线
https://blog.csdn.net/jackhh1/article/details/102763999
加速器执行训练步骤N时,CPU正在为步骤N+1准备数据,这样可以大大减少CPU和GPU的空闲时间
回调函数
https://keras-cn.readthedocs.io/en/latest/other/callbacks/
术语表
对数(logits)
分类模型生成的原始(非标准化)预测向量,通常会传递给标准化函数.如果模型要解决多类别分类问题,则对数通常变成 softmax 函数的输入.之后,softmax 函数会生成一个(标准化)概率向量,对应于每个可能的类别.
tf.compat
提供兼容性功能
tf.compat.v1.reset_default_graph() #清除默认图形堆栈并重置全局默认图形。
具体例子看这个博客https://blog.csdn.net/duanlianvip/article/details/98626111,我的理解暂时就是重新开始,防止在以前的基础上生成新节点
tf.io
def process_example_paths(example):#先读取再按照对应格式解码
return {'feature': tf.io.decode_jpeg(tf.io.read_file(example[0]), channels=3),
'label': tf.io.decode_png(tf.io.read_file(example[1]), channels=1)}
#获得如下
#tf.Tensor([600 394 3], shape=(3,), dtype=int32)
#tf.Tensor([600 394 1], shape=(3,), dtype=int32)
tf.keras
tensorflow的高级API
Overview
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
Input
Input()
被用来实例化一个Keras tensor。
tf.keras.Input(
shape=None,#一个shape tuple(int),不包括batch size.例如,shape =(32,)表示期望的输入将是batches of 32-dim vectors.
#该元组的元素可以为None;“None”元素代表形状未知的尺寸。
batch_size=None,#optional static batch size (integer).
name=None,#一个可选的名字string for the layer.应该unique,如果不指定会被自动生成
dtype=None, sparse=False, tensor=None,
ragged=False, **kwargs
)->A tensor
Keras张量是一个TensorFlow symbolic tensor object,我们使用某些属性对其进行了扩充,这些属性使我们仅通过了解模型的输入和输出即可构建Keras模型。
例如,如果a
,b
,c
是Keras Tensor,那么可能:model=Model(input=[a,b],output=c)
# this is a logistic regression in Keras
x = Input(shape=(32,))
y = Dense(16, activation='softmax')(x)
model = Model(x, y)
Note that even if eager execution is enabled, Input
produces a symbolic tensor (i.e. a placeholder). This symbolic tensor can be used with other TensorFlow ops。
Model
Model
将layers组合成一个具有training和inference特征的对象.
tf.keras.Model(
*args, **kwargs
)
Model的model.__call__()
的参数:
- inputs:模型的输入,一个
keras.Input
对象或一个keras.Input
对象的列表 - outputs:模型的输出
- name:String,模型的名字
有两种方式来实例化一个Model
:
1 使用”Functional API”,从input
开始,通过连接起来的layer的calls来指定模型的前向传播,并且最终从输入和输出创建你的模型。
import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
2 By subclassing the Model
class:这种情况下,你将你的layers定义在__init__
并且你应该实现模型的前向传播在__call__
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super(MyModel, self).__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
你可以选择性的设立一个training
argument(boolean) 在call
,你可以使用这个参数在训练阶段和推断阶段指定不同的行为:
def call(self, inputs, training=False):
x = self.dense1(inputs)
if training:
x = self.dropout(x, training=training)
return self.dense2(x)
模型一旦建立,你可以为你的模型配置losses和metrics 通过model.compile()
,训练模型通过model.fit()
,或者使用model.predict()
预测模型。
compile
配置模型用于训练
compile(
optimizer='rmsprop',#String(name of optimizer)or optimizer instance.See tf.keras.optimizers.
loss=None,# String(name of objective function),objective function or tf.keras.losses.Loss 实例.
metrics=None,#List of metrics在训练和测试阶段被评估.里面的每一个可以是a string(name of a built-in function),
#function,或者a tf.keras.metrics.Metric实例.
loss_weights=None,
weighted_metrics=None, run_eagerly=None, steps_per_execution=None, **kwargs
)
#对于loss,An objective function is any callable with the signature
loss = fn(y_true,y_pred)
#y_true为GT,shape=[batch_size, d0,...,dN] y_pred为预测值,shape=[batch_size, d0,...,dN]
#它返回一个加权损失浮点张量.如果使用自定义Loss实例,并且将reduce设置为NONE,则返回值的形状为[batch_size,d0,...,dN-1],即每个样本或每个时间步的loss;否则,它是一个scalar.如果模型具有多个输出,则可以通过传递dict或a list of losses来在每个输出上使用不同的loss.然后,模型将minimized的loss将是所有单个loss的总和。
#对于metrics,经典的你可以使用
metrics = ['accuracy']
#A function is any callable with the signature
result = fn(y_true, y_pred)
#对于多输出模型的不同输出指定不同metrics,你也可以传递一个dict,例如
metrics={'output_a' : 'accuracy', 'output_b' : ['accuracy', 'mse']}
#你也可以传递一个list(len = len(outputs))
metrics=[['accuracy'], ['accuracy', 'mse']]
metrics=['accuracy', ['accuracy', 'mse']]
#当你传递string例如'accuracy'或'acc',我们将它们one of
#tf.keras.metrics.BinaryAccuracy,
#tf.keras.metrics.CategoricalAccuracy,
#tf.keras.metrics.SparseCategoricalAccuracy
#基于使用的损失函数和模型输出的shape选择一个,我们对'crossentropy'和'ce'做类似的转换.
fit
为模型训练固定的epoch。
fit(
x=None,#Input data
y=None,#Target data
batch_size=None,#int或None,如果未指定,默认为batch_size=32,如果x是datasets,generators或者keras.util.Swquence
#无需指定,(因为他们自己生成batches)
epochs=1,#int
verbose=1,#0,1,2.详细模式, 0=silent,1=progress bar,2=one line per epoch.
#请注意,progress bar在logged到文件时不是特别有用,因此,如果不以交互方式运行(例如,在生产环境中),建议使用verbose = 2.
callbacks=None,
validation_split=0.0, validation_data=None, shuffle=True, class_weight=None,
sample_weight=None, initial_epoch=0, steps_per_epoch=None,
validation_steps=None, validation_batch_size=None, validation_freq=1,
max_queue_size=10, workers=1, use_multiprocessing=False
)
#对于input data,可以是
#A Numpy array(or array-like),或者a list of arrays(如果模型有多个输入)
#A Tensorflow tensor,或者a list of tensors(如果模型有多个输入)
#A dict 映射input names到相应的array/tensors,如果模型有named inputs
#A tf.data dataset,其应该返回要么是(inputs,targets)要么是(inputs, targets, sample_weights)
#A generator or keras.util.Sequence返回(inputs, targets)或者(inputs, targets, sample_weights)
#对于target_data,与x类似,可以是Numpy arrays或者Tensorflow tensor(s),但是必须与x保持一致.当x是dataset,generator或者keras.utils.Sequence时,y不应该被指定.
evalute
返回测试模式下的loss value & metrics values.
evaluate(
x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None,
callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False,
return_dict=False
)->Scalar test loss#(如果模型只有一个输出且没有metrics)
->or list of scalars#(如果模型有多个输出且有metrics)
#属性modle.metrics_name将为你展示标量输出的标签.
predict
生成输入样本的输出预测。
计算是分批进行的。 此方法专为在大规模输入中的性能而设计。
对于适合one batch的少量输入,建议您直接使用__call__
来加快执行速度,例如,如果您有tf.keras.layers.BatchNormalization
这样的在inference中的行为有所不同的layers,则可以使用model(x)
或model(x, training = False)
. 另外,请注意,test loss不受诸如noise和dropout之类的regularization layers的影响。
predict(
x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10,
workers=1, use_multiprocessing=False
)->Numpy array(s) of predictions.
Sequential
Sequential
组合一个layers的线性堆叠成一个 tf.keras.Model
。
tf.keras.Sequential(
layers=None,#Optional list of layers to add to the model.
name=None#
)
#eg:
# Optionally, the first layer can receive an `input_shape` argument:
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(8, input_shape=(16,)))
# Afterwards, we do automatic shape inference:
model.add(tf.keras.layers.Dense(4))
#注意,您也可以省略“ input_shape”参数.在这种情况下,直到第一次调用training/evaluation方法(由于尚未构建),模型才具有任何权重.
#这个input_shape是指单个元素的维度,不算batch_size那个维度.
tf.keras.backend
https://keras-cn.readthedocs.io/en/latest/backend/
keras后端API,有Theano和Tensorflow
tf.keras.backend.clear_session()
#结束当前的TF计算图,并新建一个。有效的避免模型/层的混乱
tf.keras.datasets
Overview
- boston_housing
- cifar10
- cifar100
- fashion_mnist
- imdb
- mnist
- reuters
mnist
tf.keras.datasets.mnist.load_data(
path='mnist.npz' #本地缓存的名字,不设置的话默认就是这个了
)
tf.keras.models
tf.keras.models.load_model(filepath, custom_objects=None, compile=True, options=None)
#可选
#compile:布尔值,是否在加载后编译模型
#options:可选
tf.keras.utils
tf.keras.utils.plot_model
tf.keras.layers
tf.keras.layers.Conv2D
该层创建a conv kernel,该conv kernel与该层input进行卷积以产生a tensor of outpus. 如果use_bias
为True,则会创建一个bias vector并将其添加到outputs中。 最后,如果activation
不为None
,则它也将应用于输出。
当使用该层作为model的第一个layer时,要提供关键的input_shape
(tuple of integers),eg,input_shape=(128,128,3)
对于128x128 RGB图片如果data_format="channels_last"
tf.keras.layers.Conv2D(
filters,#卷积过滤器的数量,对应输出的维度
kernel_size, strides=(1, 1), padding='valid',
data_format=None, dilation_rate=(1, 1), groups=1, activation=None,
use_bias=True, kernel_initializer='glorot_uniform',
bias_initializer='zeros', kernel_regularizer=None,
bias_regularizer=None, activity_regularizer=None, kernel_constraint=None,
bias_constraint=None, **kwargs
)->A tensor of rank 4+ representing activation(conv2d(inputs, kernel) + bias)
# The inputs are 28x28 RGB images with `channels_last` and the batch
# size is 4.
input_shape = (4, 28, 28, 3)
x = tf.random.normal(input_shape)
y = tf.keras.layers.Conv2D(2, 3, activation='relu', input_shape=input_shape[1:])(x)#不用batch
print(y.shape)
$input_shape$
4+D tensor with shape: batch_shape + (channels, rows, cols)
if data_format='channels_first'
or 4+D tensor with shape: batch_shape + (rows, cols, channels)
if data_format='channels_last'
.
$output_shape$
4+D tensor with shape: batch_shape + (filters, new_rows, new_cols)
if data_format='channels_first'
or 4+D tensor with shape: batch_shape + (new_rows, new_cols, filters)
if data_format='channels_last'
.
rows
and cols
values might have changed due to padding.
tf.keras.layers.Dense
全连接
tf.keras.layers.Dense(
units,#正整数,输出空间的维数
activation=None,#激活函数
use_bias=True,#是否使用bias vector
kernel_initializer='glorot_uniform',
bias_initializer='zeros', kernel_regularizer=None,
bias_regularizer=None, activity_regularizer=None, kernel_constraint=None,
bias_constraint=None, **kwargs
)
Dense
实现了这个操作:output = activation(dot(input, kernel) +bias)
其中activation
是element-wise激活函数作为activation
参数传递进来,kernel
是被layer创建的权重矩阵,bias
是由layers创建的bias vecvor(只在use_bias
是True
的时候)
此外,layer被调用一次之后,属性便无法更改(可训练属性除外).
$input_shape$
N维张量的shape:(batch_size,...,input_dim)
.最常见的情况是(batch_size,input_dim)
的输入.
$output_shape$
N维张量的shape:(batch_size,...,units)
.例如,一个2D输入的shape:(batch_size,input_dim)
,输入可能有shape:(batch_size,units)
tf.keras.layers.Flatten
重新格式化数据$(B,H,W,C)\to(B,H\times W\times C)$ $(B,)\to(B,1)$
tf.keras.layers.Flatten(
data_format=None,#data_format有channel_last(默认)和channel_first
**kwargs#
)
tf.keras.layers.Softmax
Softamx激活函数.
tf.keras.layers.Softmax(
axis=-1,#Integer,or list of Integers,softmax应用的维度
**kwargs
)
tf.keras.losses
Built-in loss functions.
tf.keras.losses.SparseCategoricalCrossentropy
计算labels和predictions之间的crossentropy。当有两个或者更多label类别时使用。我们期望labels是integers。如果你想让labels使用one-hot
方式,请使用
CategoricalCrossentropy
损失.
tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=False,#y_pred是否应该是一个logits tensor.
#Using from_logits=True may be more numerically stable.
reduction=losses_utils.ReductionV2.AUTO,#(Optional) Type of tf.keras.losses.Reduction to apply to loss.
#默认值是AUTO,意味着reduction操作会根据使用的上下文决定。绝大多数情况默认为SUM_OVER_BATCH_SIZE.
name='sparse_categorical_crossentropy'#可选的名字对于该op
)
对于y_pred
应该有# classes
个浮点数每个特征,而对于y_true
一个浮点数每个特征。
y_true
shape=[batch_size]
,而y_pred
shape=[batch_size, num_classes]
y_true = [1, 2]
y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
# Using 'auto'/'sum_over_batch_size' reduction type.
scce = tf.keras.losses.SparseCategoricalCrossentropy()
scce(y_true, y_pred).numpy()
__call__
__call__(
y_true, y_pred, sample_weight=None
)