Keras如何用于模型的训练、评估和推理?

Tensorflow 是 Google 提供的机器学习框架。它是一个与 Python 结合使用以实现算法、深度学习应用程序等的开源框架。它用于研究和生产目的。它具有有助于快速执行复杂数学运算的优化技术。

可以使用以下代码行在 Windows 上安装“tensorflow”包 -

pip install tensorflow

Keras 是作为 ONEIROS(开放式神经电子智能机器人操作系统)项目研究的一部分而开发的。Keras 是一个深度学习 API,它是用 Python 编写的。它是一种高级 API,具有有助于解决机器学习问题的高效界面。

它具有高度可扩展性,并具有跨平台功能。这意味着 Keras 可以在 TPU 或 GPU 集群上运行。Keras 模型也可以导出以在 Web 浏览器或手机中运行。

Keras 已经存在于 Tensorflow 包中。可以使用以下代码行访问它。

import tensorflow
from tensorflow import keras

与使用顺序 API 创建的模型相比,Keras 函数式 API 有助于创建更灵活的模型。函数式 API 可以处理具有非线性拓扑结构的模型,可以共享层并处理多个输入和输出。深度学习模型通常是包含多个层的有向无环图 (DAG)。函数式 API 有助于构建层图。

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

示例

print("Load the MNIST data")
print("Split data into training and test data")
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
print("Reshape the data for better training")
x_train = x_train.reshape(60000, 784).astype("float32") / 255
x_test = x_test.reshape(10000, 784).astype("float32") / 255
print("Compile the model")
model.compile(
   loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
   optimizer=keras.optimizers.RMSprop(),
   metrics=["accuracy"],
)
print("Fit the data to the model")
history = model.fit(x_train, y_train, batch_size=64, epochs=2, validation_split=0.2)
test_scores = model.evaluate(x_test, y_test, verbose=2)
print("与模型相关的损失:", test_scores[0])
print("模型精度:", test_scores[1])

代码信用 - https://www.tensorflow.org/guide/keras/functional

输出结果

Load the MNIST data
Split data into training and test data
Reshape the data for better training
Compile the model
Fit the data to the model
Epoch 1/2
750/750 [==============================] - 3s 3ms/step - loss: 0.5768 - accuracy: 0.8394 -
val_loss: 0.2015 - val_accuracy: 0.9405
Epoch 2/2
750/750 [==============================] - 2s 3ms/step - loss: 0.1720 - accuracy: 0.9495 -
val_loss: 0.1462 - val_accuracy: 0.9580
313/313 - 0s - loss: 0.1433 - accuracy: 0.9584
与模型相关的损失: 0.14328785240650177
模型精度: 0.9584000110626221

解释

  • 输入数据(MNIST 数据)被加载到环境中。

  • 数据分为训练集和测试集。

  • 数据经过重新整形,以提高其准确性。

  • 模型被构建和编译。

  • 然后它适合训练数据。

  • 与训练相关的准确率和损失显示在控制台上。