如何使用 Tensorflow 编译使用 Python 的模型?
pythonserver side programmingprogrammingtensorflow
可以使用‘compile’方法编译在 Tensorflow 中创建的模型。使用‘SparseCategoricalCrossentropy’方法计算损失。
阅读更多: 什么是 TensorFlow,以及 Keras 如何与 TensorFlow 配合使用来创建神经网络?
我们正在使用 Google Colaboratory 来运行以下代码。 Google Colab 或 Colaboratory 可帮助在浏览器上运行 Python 代码,无需任何配置,并可免费访问 GPU(图形处理单元)。Colaboratory 是在 Jupyter Notebook 的基础上构建的。
print("The model is being compiled") model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) print("The architecture of the model") model.summary()
代码来源:https://www.tensorflow.org/tutorials/images/classification
输出
The model is being compiled The architecture of the model 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"方法显示架构摘要。