Tensorfow2.0—LowerAPI
numpy to tensorflow
Notice that NumPy uses 64-bit precision by default, while Tensor‐ Flow uses 32-bit.
This is because 32-bit precision is generally more than enough for neural networks, plus it runs faster and uses less RAM.
So when you create a tensor from a NumPy array, make sure to set dtype=tf.float32.
Customizing Models and Training Algorithms
- Custom Loss Functions
1 | def huber_fn(y_true, y_pred): |
1 | input_shape = X_train.shape[1:] |
Saving and Loading Models That Contain Custom Components
- 需求:对于自定义的损失函数,需要把阈值threshold设为超参数,需要继承
keras.losses.Loss
类,并重载get_config()
方法:
The constructor accepts kwargs and passes them to the parent constructor, which handles standard hyperparameters: the name of the loss and the reduction algorithm to use to aggregate the individual instance losses.
By default, it is “sum_over_batch_size”, which means that the loss will be the sum of the instance losses, weighted by the sample weights, if any, and divided by the batch size
The call() method takes the labels and predictions, computes all the instance losses, and returns them.
The get_config() method returns a dictionary mapping each hyperparameter name to its value
1 | class HuberLoss(keras.losses.Loss): |
1 | model = keras.models.Sequential([ |
- Save & load:
1 | model.save("my_model_with_a_custom_loss_class.h5") |
Custom Activation Functions, Initializers, Regularizers, and Constraints
1 | def my_softplus(z): # return value is just tf.nn.softplus(z) |
继承实现:
- keras.regularizers.Regularizer,
- keras.constraints.Constraint,
- keras.initializers.Initializer
- keras.layers.Layer (for any layer, including activation functions)
Like Custom Regularizer:不需要调用父类的
__call__
等方法。
1 | class MyL1Regularizer(keras.regularizers.Regularizer): |
因为keras.regularizers.Regularizer
没有实现__call__
和get_config()
的:
1 | def __call__(self, x): |
- WARNING:
- must implement the
call()
method for losses, layers (including activa‐ tion functions), and models, - or the
__call__()
method for regularizers, initializers, and constraints.
- must implement the