当前位置:   article > 正文

CNN应用Keras Tuner寻找最佳Hidden Layers层数和神经元数量

CNN应用Keras Tuner寻找最佳Hidden Layers层数和神经元数量

介绍: 

Keras Tuner是一种用于优化Keras模型超参数的开源Python库。它允许您通过自动化搜索算法来寻找最佳的超参数组合,以提高模型的性能。Keras Tuner提供了一系列内置的超参数搜索算法,如随机搜索、网格搜索、贝叶斯优化等。它还支持自定义搜索空间和搜索算法。通过使用Keras Tuner,您可以更轻松地优化模型的性能,节省调参的时间和精力。

数据: 

  1. from tensorflow.keras.datasets import fashion_mnist
  2. (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
  3. '''
  4. Label Description
  5. 0 T-shirt/top
  6. 1 Trouser
  7. 2 Pullover
  8. 3 Dress
  9. 4 Coat
  10. 5 Sandal
  11. 6 Shirt
  12. 7 Sneaker
  13. 8 Bag
  14. 9 Ankle boot
  15. '''
  16. import matplotlib.pyplot as plt
  17. %matplotlib inline
  18. print(y_test[0])
  19. plt.imshow(x_test[0], cmap="gray")
  20. #each having 1 channel (grayscale, it would have been 3 in the case of color, 1 each for Red, Green and Blue)

建模:

  1. x_train = x_train.reshape(-1, 28, 28, 1)
  2. x_test = x_test.reshape(-1, 28, 28, 1)
  3. from tensorflow import keras
  4. from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Activation
  5. import os
  6. os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
  7. model = keras.models.Sequential()
  8. model.add(Conv2D(32, (3, 3), input_shape=x_train.shape[1:]))
  9. model.add(Activation('relu'))
  10. model.add(MaxPooling2D(pool_size=(2, 2)))
  11. model.add(Conv2D(32, (3, 3)))
  12. model.add(Activation('relu'))
  13. model.add(MaxPooling2D(pool_size=(2, 2)))
  14. model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
  15. model.add(Dense(10))
  16. model.add(Activation("softmax"))
  17. model.compile(optimizer="adam",
  18. loss="sparse_categorical_crossentropy",
  19. metrics=["accuracy"])
  20. model.fit(x_train, y_train, batch_size=64, epochs=1, validation_data = (x_test, y_test))

 

 Keras Tuner:

  1. from kerastuner.tuners import RandomSearch
  2. from kerastuner.engine.hyperparameters import HyperParameters
  3. def build_model(hp): # random search passes this hyperparameter() object
  4. model = keras.models.Sequential()
  5. model.add(Conv2D(hp.Int('input_units',
  6. min_value=32,
  7. max_value=256,
  8. step=32), (3, 3), input_shape=x_train.shape[1:]))
  9. model.add(Activation('relu'))
  10. model.add(MaxPooling2D(pool_size=(2, 2)))
  11. for i in range(hp.Int('n_layers', 1, 4)): # adding variation of layers.
  12. model.add(Conv2D(hp.Int(f'conv_{i}_units',
  13. min_value=32,
  14. max_value=256,
  15. step=32), (3, 3)))
  16. model.add(Activation('relu'))
  17. model.add(Flatten())
  18. model.add(Dense(10))
  19. model.add(Activation("softmax"))
  20. model.compile(optimizer="adam",
  21. loss="sparse_categorical_crossentropy",
  22. metrics=["accuracy"])
  23. return model
  24. tuner = RandomSearch(
  25. build_model,
  26. objective='val_accuracy',
  27. max_trials=1, # how many model variations to test?
  28. executions_per_trial=1, # how many trials per variation? (same model could perform differently)
  29. directory='Lesson56',
  30. project_name='Optimise')
  31. tuner.search(x=x_train,
  32. y=y_train,
  33. verbose=1, # just slapping this here bc jupyter notebook. The console out was getting messy.
  34. epochs=1,
  35. batch_size=64,
  36. #callbacks=[tensorboard], # if you have callbacks like tensorboard, they go here.
  37. validation_data=(x_test, y_test))

tuner.results_summary()

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号