如何使用 Tensorflow 来使用 Python 训练模型?

pythonserver side programmingprogrammingtensorflow

可以使用 Tensorflow 中的‘train’方法训练模型,其中指定了 epoch(数据必须训练才能适合模型的次数)和训练数据。

阅读更多: 什么是 TensorFlow,以及 Keras 如何与 TensorFlow 配合使用来创建神经网络?

我们正在使用 Google Colaboratory 来运行以下代码。 Google Colab 或 Colaboratory 可帮助在浏览器上运行 Python 代码,无需配置,可免费访问 GPU(图形处理单元)。Colaboratory 建立在 Jupyter Notebook 之上。

print("The model is being training")
epochs=12
history = model.fit(
   train_ds,
   validation_data=val_ds,
   epochs=epochs
)

代码来源:https://www.tensorflow.org/tutorials/images/classification

输出

The model is being training
Epoch 1/12
92/92 [==============================] - 94s 1s/step - loss: 1.6007 - accuracy: 0.3411 - val_loss: 1.0708 - val_accuracy: 0.5627
Epoch 2/12
92/92 [==============================] - 92s 995ms/step - loss: 1.0138 - accuracy: 0.5843 - val_loss: 0.9451 - val_accuracy: 0.6458
Epoch 3/12
92/92 [==============================] - 91s 990ms/step - loss: 0.8382 - accuracy: 0.6767 - val_loss: 0.9054 - val_accuracy: 0.6471
Epoch 4/12
92/92 [==============================] - 90s 984ms/step - loss: 0.6362 - accuracy: 0.7580 - val_loss: 0.8872 - val_accuracy: 0.6540
Epoch 5/12
92/92 [==============================] - 94s 1s/step - loss: 0.4125 - accuracy: 0.8572 - val_loss: 0.9114 - val_accuracy: 0.6676
Epoch 6/12
92/92 [==============================] - 91s 988ms/step - loss: 0.2460 - accuracy: 0.9207 - val_loss: 1.0891 - val_accuracy: 0.6757
Epoch 7/12
92/92 [==============================] - 91s 988ms/step - loss: 0.1721 - accuracy: 0.9532 - val_loss: 1.2619 - val_accuracy: 0.6635
Epoch 8/12
92/92 [==============================] - 90s 983ms/step - loss: 0.0658 - accuracy: 0.9823 - val_loss: 1.4119 - val_accuracy: 0.6703
Epoch 9/12
92/92 [==============================] - 90s 983ms/step - loss: 0.0556 - accuracy: 0.9865 - val_loss: 1.6113 - val_accuracy: 0.6090
Epoch 10/12
92/92 [==============================] - 91s 992ms/step - loss: 0.0805 - accuracy: 0.9729 - val_loss: 1.9744 - val_accuracy: 0.6390
Epoch 11/12
92/92 [==============================] - 90s 979ms/step - loss: 0.0545 - accuracy: 0.9838 - val_loss: 1.9303 - val_accuracy: 0.6662
Epoch 12/12
92/92 [==============================] - 96s 1s/step - loss: 0.0176 - accuracy: 0.9961 - val_loss: 1.8234 - val_accuracy: 0.6540

解释

  • 模型经过训练以适合数据。
  • 这是使用"fit"方法完成的。

相关文章