如何使用 Python 程序和 Keras 训练模型?
Keras 是作为 ONEIROS 项目(开放式神经电子智能机器人操作系统)研究的一部分开发的。Keras 是一个用 Python 编写的深度学习 API。它是一个高级 API,具有高效的界面,有助于解决机器学习问题。它运行在 TensorFlow 框架之上。它的构建是为了帮助快速进行实验。它提供了开发和封装机器学习解决方案所需的必要抽象和构建块。
它具有高度的可扩展性并具有跨平台能力。这意味着 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("The model is being plotted") keras.utils.plot_model(model, "my_resnet.png", show_shapes=True) print("Split the data into training and test data") (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data() print("Convert the type of data to float") x_train = x_train.astype("float32") / 255.0 x_test = x_test.astype("float32") / 255.0 y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) print("Compiling the model") model.compile( optimizer=keras.optimizers.RMSprop(1e-3), loss=keras.losses.CategoricalCrossentropy(from_logits=True), metrics=["acc"], ) model.fit(x_train[:2000], y_train[:2000], batch_size=64, epochs=2, validation_split=0.2)
代码来源:https://tensorflowcn.cn/guide/keras/functional
输出
The model is being plotted Split the data into training and test data Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz 170500096/170498071 [==============================] - 2s 0us/step Convert the type of data to float Compiling the model Epoch 1/2 25/25 [==============================] - 9s 332ms/step - loss: 2.3163 - acc: 0.1028 - val_loss: 2.2962 - val_acc: 0.1175 Epoch 2/2 25/25 [==============================] - 12s 492ms/step - loss: 2.3155 - acc: 0.1175 - val_loss: 2.2606 - val_acc: 0.1200 <tensorflow.python.keras.callbacks.History at 0x7f48d3ecfb00>
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
解释
输入数据被分成训练数据集和测试数据集。
数据类型转换为“float”类型。
使用“compile”方法编译模型。
使用“fit”方法将模型拟合到训练数据。