Python 如何使用Python编译Tensorflow模型?
使用Tensorflow创建的模型可以使用“compile”方法进行编译。使用“SparseCategoricalCrossentropy”方法计算损失。
我们在Google Colaboratory上运行下面的代码。Google Colab或Colaboratory可以在浏览器上运行Python代码,无需任何配置,并且可以免费访问GPU(图形处理单元)。Colaboratory建立在Jupyter Notebook之上。
print("正在编译模型")
model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
print("模型架构")
model.summary()
代码来源: https://www.tensorflow.org/tutorials/images/classification
阅读更多:Python 教程
输出
正在编译模型
模型架构
Model: "sequential_2"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
rescaling_1 (Rescaling) (None, 180, 180, 3) 0
_________________________________________________________________
conv2d_6 (Conv2D) (None, 180, 180, 16) 448
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 90, 90, 16) 0
_________________________________________________________________
conv2d_7 (Conv2D) (None, 90, 90, 32) 4640
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 45, 45, 32) 0
_________________________________________________________________
conv2d_8 (Conv2D) (None, 45, 45, 64) 18496
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 22, 22, 64) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 30976) 0
_________________________________________________________________
dense_2 (Dense) (None, 128) 3965056
_________________________________________________________________
dense_3 (Dense) (None, 5) 645
=================================================================
Total params: 3,989,285
Trainable params: 3,989,285
Non-trainable params: 0
_________________________________________________________________
说明
- 使用optimizers.Adam优化器和losses.SparseCategoricalCrossentropy损失函数。
- 可以使用metrics参数查看每个训练时期的训练和验证准确性。
- 一旦编译模型,就可以使用“summary”方法显示架构的摘要。
极客教程