如何使用 Tensorflow 在 Python 中训练模型?


Tensorflow 中可以使用“train”方法训练模型,其中指定了训练数据和 epochs(模型拟合所需的数据训练次数)。

了解更多: 什么是 TensorFlow?Keras 如何与 TensorFlow 协同工作以创建神经网络?

我们使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 帮助通过浏览器运行 Python 代码,并且需要零配置和免费访问 GPU(图形处理单元)。Colaboratory 构建在 Jupyter Notebook 之上。

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

代码来源:https://tensorflowcn.cn/tutorials/images/classification

输出

The model is being trained
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”方法完成的。

更新于:2021-02-20

132 人次浏览

开启你的 职业生涯

完成课程获得认证

开始
广告