如何使用 Keras 使用 Python 程序训练模型?
Keras是作为ONEIROS(开放式神经电子智能机器人操作系统)项目研究的一部分而开发的。Keras是一个深度学习API,它是用Python编写的。它是一种高级API,具有有助于解决机器学习问题的高效界面。它运行在Tensorflow框架之上。它旨在帮助快速进行实验。它提供了在开发和封装机器学习解决方案中必不可少的基本抽象和构建块。
它具有高度可扩展性,并具有跨平台功能。这意味着Keras可以在TPU或GPU集群上运行。Keras模型也可以导出以在Web浏览器或手机中运行。
Keras已经存在于Tensorflow包中。可以使用以下代码行访问它。
import tensorflow from tensorflow import keras
与使用顺序API创建的模型相比,Keras函数式API有助于创建更灵活的模型。函数式API可以处理具有非线性拓扑结构的模型,可以共享层并处理多个输入和输出。深度学习模型通常是包含多个层的有向无环图(DAG)。函数式API有助于构建层图。
我们正在使用GoogleColaboratory运行以下代码。GoogleColab或Colaboratory帮助在浏览器上运行Python代码,并且需要零配置和免费访问GPU(图形处理单元)。Colaboratory建立在JupyterNotebook之上。以下是训练模型的代码片段-
示例
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://www.tensorflow.org/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
解释
输入数据分为训练数据集和测试数据集。
数据类型转换为“float”类型。
该模型是使用“编译”方法编译的。
'fit'方法用于将模型拟合到训练数据。