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
Keras 函数式 API 有助于创建比使用顺序 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://tensorflowcn.cn/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 数据)加载到环境中。
数据被分成训练集和测试集。
数据被重新整形,使其准确性得到提高。
模型被构建和编译。
然后将其拟合到训练数据。
与训练相关的准确性和损失显示在控制台上。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP