如何使用Tensorflow训练和编译CNN模型?
卷积神经网络可以使用“train”方法和“fit”方法分别进行训练和编译。“fit”方法中提供了“epoch”值。
阅读更多: 什么是TensorFlow以及Keras如何与TensorFlow一起创建神经网络?
我们将使用Keras Sequential API,它有助于构建一个顺序模型,用于处理简单的层堆叠,其中每一层都只有一个输入张量和一个输出张量。
包含至少一层卷积层的神经网络称为卷积神经网络。卷积神经网络已被用于针对特定类型的问题(例如图像识别)产生良好的结果。
我们使用Google Colaboratory运行以下代码。Google Colab或Colaboratory有助于在浏览器上运行Python代码,无需任何配置,并且可以免费访问GPU(图形处理单元)。Colaboratory构建在Jupyter Notebook之上。
print("Compiling the model") model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) print("Training the model to fit the data") history = model.fit(train_images, train_labels, epochs=10,validation_data=(test_images, test_labels))
代码来源:https://tensorflowcn.cn/tutorials/images/cnn
输出
Compiling the model Training the model to fit the data Epoch 1/10 1563/1563 [==============================] - 70s 44ms/step - loss: 1.7408 - accuracy: 0.3557 - val_loss: 1.2260 - val_accuracy: 0.5509 Epoch 2/10 1563/1563 [==============================] - 67s 43ms/step - loss: 1.1928 - accuracy: 0.5751 - val_loss: 1.0800 - val_accuracy: 0.6159 Epoch 3/10 1563/1563 [==============================] - 68s 43ms/step - loss: 1.0330 - accuracy: 0.6396 - val_loss: 0.9791 - val_accuracy: 0.6562 Epoch 4/10 1563/1563 [==============================] - 66s 43ms/step - loss: 0.9197 - accuracy: 0.6782 - val_loss: 0.9488 - val_accuracy: 0.6677 Epoch 5/10 1563/1563 [==============================] - 65s 42ms/step - loss: 0.8388 - accuracy: 0.7043 - val_loss: 0.9090 - val_accuracy: 0.6851 Epoch 6/10 1563/1563 [==============================] - 66s 42ms/step - loss: 0.7755 - accuracy: 0.7279 - val_loss: 0.8694 - val_accuracy: 0.6944 Epoch 7/10 1563/1563 [==============================] - 66s 42ms/step - loss: 0.7107 - accuracy: 0.7494 - val_loss: 0.9152 - val_accuracy: 0.6929 Epoch 8/10 1563/1563 [==============================] - 65s 42ms/step - loss: 0.6674 - accuracy: 0.7649 - val_loss: 0.8613 - val_accuracy: 0.7045 Epoch 9/10 1563/1563 [==============================] - 66s 42ms/step - loss: 0.6288 - accuracy: 0.7771 - val_loss: 0.8788 - val_accuracy: 0.7026 Epoch 10/10 1563/1563 [==============================] - 66s 42ms/step - loss: 0.5913 - accuracy: 0.7953 - val_loss: 0.8884 - val_accuracy: 0.7053
解释
- 模型已编译。
- 下一步是训练模型以适应训练数据。
- 训练数据的步骤数为10。
广告