tensorflow.keras.layers keras.Model 自定义层应用
tensorflow.keras.layers keras.Model 自定义层应用
1 | import tensorflow as tf |
数据预处理
1 | def preprocess(x, y): |
1 | 自定义Layer |
1 | class MyDense(layers.Layer): |
自定义Model
继承keras.Model可使用complie fit 等方法
1 | class MyModel(keras.Model): |
1 | batchsz = 128 |
datasets: (60000, 28, 28) (60000,) 0 255
(128, 784) (128, 10)
创建模型
summary()必须在fit 或 build之后使用
1 | network = MyModel() |
Model: "my_model_8"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
my_dense_40 (MyDense) multiple 200960
_________________________________________________________________
my_dense_41 (MyDense) multiple 32896
_________________________________________________________________
my_dense_42 (MyDense) multiple 8256
_________________________________________________________________
my_dense_43 (MyDense) multiple 2080
_________________________________________________________________
my_dense_44 (MyDense) multiple 330
=================================================================
Total params: 244,522
Trainable params: 244,522
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
469/469 [==============================] - 10s 22ms/step - loss: 0.3078 - accuracy: 0.9076
Epoch 2/5
469/469 [==============================] - 13s 28ms/step - loss: 0.1409 - accuracy: 0.9600 - val_loss: 0.1318 - val_accuracy: 0.9641
Epoch 3/5
469/469 [==============================] - 13s 27ms/step - loss: 0.1125 - accuracy: 0.9680
Epoch 4/5
469/469 [==============================] - 16s 35ms/step - loss: 0.0984 - accuracy: 0.9724 - val_loss: 0.1196 - val_accuracy: 0.9673
Epoch 5/5
469/469 [==============================] - 15s 32ms/step - loss: 0.0875 - accuracy: 0.9760
79/79 [==============================] - 3s 33ms/step - loss: 0.1224 - accuracy: 0.9704
[0.12237951139141393, 0.9704]
模型预测
1 | sample = next(iter(ds_val)) |
tf.Tensor(
[7 2 1 0 4 1 4 9 6 9 0 6 9 0 1 5 9 7 3 4 9 6 6 5 4 0 7 4 0 1 3 1 3 4 7 2 7
1 2 1 1 7 4 2 3 5 1 2 4 4 6 3 5 5 6 0 4 1 9 5 7 8 9 3 7 4 6 4 3 0 7 0 2 9
1 7 3 2 9 7 7 6 2 7 8 4 7 3 6 1 3 6 9 3 1 4 1 7 6 9 6 0 5 4 9 9 2 1 9 4 8
7 3 9 7 9 4 4 9 2 5 4 7 6 7 9 0 5], shape=(128,), dtype=int64)
tf.Tensor(
[7 2 1 0 4 1 4 9 5 9 0 6 9 0 1 5 9 7 3 4 9 6 6 5 4 0 7 4 0 1 3 1 3 4 7 2 7
1 2 1 1 7 4 2 3 5 1 2 4 4 6 3 5 5 6 0 4 1 9 5 7 8 9 3 7 4 6 4 3 0 7 0 2 9
1 7 3 2 9 7 7 6 2 7 8 4 7 3 6 1 3 6 9 3 1 4 1 7 6 9 6 0 5 4 9 9 2 1 9 4 8
7 3 9 7 4 4 4 9 2 5 4 7 6 7 9 0 5], shape=(128,), dtype=int64)
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 没有胡子的猫Asimok!
评论