Tensorfow2.0—初步Keras
激活函数
1、Sigmoid函数,又称为Logistic函数,特点:输出范围[0,1]。
1 | def Sigmoid(z): |
2、Tanh函数:$\text{Tanh}(z)=2\text{Sigmoid}(2z) - 1$ ,特点:output范围在[-1, 1]之间,效果是在训练初期每层网络的输出都或多或少的聚集在0附近,*可以加快收敛。
3、ReLU函数,特点:0点不可导。
1 | def relu(z): |
可以用两点估计法计算下函数梯度:
1 | def derivative(f, z, eps=0.000001): |
MLP
1 | model = keras.models.Sequential() |
1 | ## tf.keras.backend.clear_session will discard the values resides in the variable defined in the graph |
可用得到模型相关信息:
1 | keras.utils.plot_model(model, "my_fashion_mnist_model.png", show_shapes=True) |
设置损失,优化器,度量函数:
sparse_categorical_cross entropy
:类别里存一个数的指示(Sparse labels),比如3表示第三类。
categorical_crossentropy
:相反是one-hot labels,如 [ 0, 0, 1 ] 来表示属于第三类。
转换:keras.utils.to_categorical() function
用于转换sparse labels to one-hot labels
1 | model.compile(loss="sparse_categorical_crossentropy", |
设置验证集:validation_split=0.1
tells Keras to use the last 10% of the data (before shuffling) for validation.
- Tips1: overfitting the training set :训练集上的效果很大程度上优于验证集。
字典信息:
1 | history = model.fit(X_train, y_train, epochs=30, |
- 训练集是每轮里跑的均值: the validation error is computed at the end of each epoch, while the training error is computed using a running mean during each epoch。
预测:
1 | y_proba = model.predict(X_new) |
Wide & Deep neural network
1 | input_ = keras.layers.Input(shape=X_train.shape[1:]) |
- 增加多个输入,多个输出的网络结构:
1 | input_A = keras.layers.Input(shape=[5], name="wide_input") # |
对两部分可以分配不同的损失函数,权重:
1 | model.compile(loss=["mse", "mse"], loss_weights=[0.9, 0.1], |
通过继承实现同样的模型,
优势:支持更复杂的操作,如条件,循环等;缺点: Keras cannot save or clone it;when you call the summary() method, you only get a list of layers, without any information on how they are connected to each other.
1 | class WideAndDeepModel(keras.models.Model): |
存储和加载模型
1 | model.save("my_keras_model.h5") |
训练过程中对checkpoint做保存
1 | # save_best_only=True, |
Tensorboard
1 | root_logdir = os.path.join(os.curdir, "my_logs") |
1 | $ tensorboard --logdir=./my_logs --port=6006 |
在jupyter上直接看:
1 | %load_ext tensorboard |
Fine-Tuning
- 1、Grid—Search:对超参数定义可选的list,然后组合;
- 一般GridSearchCV的参数
refit=True
,即选到了某个超参的最优值后,固定这个超参数为它,然后去塞选其他超参数的值。
- 一般GridSearchCV的参数
1 | from sklearn.model_selection import GridSearchCV |
- 2、Randomized Search:selecting a random value for each hyperparameter at every iterationn.
- 3、Ensemble Methods:把所有好的模型组合起来做分析。
Keras + GridSearch:
1、Any extra parameter you pass to the fit()
method will get passed to the underlying Keras model.
1 | def build_model(n_hidden=1, n_neurons=30, learning_rate=3e-3, input_shape=[8]): |
Keras + RandomizedSearch:
1 | from scipy.stats import reciprocal |