Keras 如何在模型的训练、评估和推理中使用?
Tensorflow 是 Google 提供的机器学习框架。它是一个与 Python 结合使用的开源框架,用于实现算法、深度学习应用程序等。它用于研究和生产目的。它具有优化技术,有助于快速执行复杂的数学运算。
可以使用以下代码行 − 在 Windows 上安装 ‘tensorflow’ 包
pip install tensorflow
Keras 是作为 ONEIROS(开放式神经电子智能机器人操作系统)项目研究的一部分开发的。Keras 是一个用 Python 编写的深度学习 API。它是一个高级 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("The loss associated with model:", test_scores[0]) print("The accuracy of the model:", 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 The loss associated with model: 0.14328785240650177 The accuracy of the model: 0.9584000110626221
解释
输入数据(MNIST 数据)被加载到环境中。
数据被分成训练集和测试集。
数据被重塑,以便其准确性变得更好。
模型被构建和编译。
然后将其与训练数据相匹配。
与训练相关的准确性和损失显示在控制台上。