Auto-Keras API详解(2)——使用示例

(一)前 言

Auto-Keras API详解(2)——使用示例
我们以MNIST数据集的识别为例来展示Auto-Keras的基本使用流程。

(二)MNIST数据集识别的Auto-Keras实现

(1)导入类库

from keras.datasets import mnist
from autokeras import ImageClassifier

(2)导入数据

在Keras中提供了若干个示例用的数据集,包括MNIST、CIFAR-10等,我们可以直接调用:

# 导入MNIST数据,并将其分配到训练集和测试集中
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape + (1,))
x_test = x_test.reshape(x_test.shape + (1,))

(3)创建图像分类器

使用Auto-Keras中的ImageClassifier创建一个图像分类器

clf = ImageClassifier(verbose=True)

(4)模型训练

指定训练时间,Auto-Keras会在指定时间内不断寻找最优网络,final_fit则是在找到最优模型后,再最后进行一次训练和验证

clf.fit(x_train, y_train, time_limit=12 * 60)
clf.final_fit(x_train, y_train, x_test, y_test, retrain=True)

(5)模型评估

对模型进行评估,打印评估结果

y = clf.evaluate(x_test, y_test)
print(y)

(6)模型保存

导出训练好的模型

clf.load_searcher().load_best_model().produce_keras_model().save('保存位置\my_model.h5')

(7)完整代码

from keras.datasets import mnist
from autokeras import ImageClassifier

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape + (1,))
x_test = x_test.reshape(x_test.shape + (1,))

clf = ImageClassifier(verbose=True)
clf.fit(x_train, y_train, time_limit=12 * 60)
clf.final_fit(x_train, y_train, x_test, y_test, retrain=True)
y = clf.evaluate(x_test, y_test)
print(y)
clf.load_searcher().load_best_model().produce_keras_model().save(r'C:\Users\12394\PycharmProjects\Auto-keras\my_model.h5')

运行代码,显示Auto-Keras正在不断进行迭代以寻找最优网络:
Auto-Keras API详解(2)——使用示例

(三)总 结

在这一节中我们介绍了Auto-Keras使用示例,有任何的疑问可以在评论区留言,我会尽快回复,谢谢支持!