-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfashion_mnist_with_kerastuner.py
66 lines (47 loc) · 2.2 KB
/
fashion_mnist_with_kerastuner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# -*- coding: utf-8 -*-
"""cnn_2.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1whV1dT9lnjhLFtyk0wqzHYlsmIpO3F65
"""
!pip install keras-tuner # its for google colab
import tensorflow as tf
import keras
import numpy as np
fashion= keras.datasets.fashion_mnist
(train_images, train_lebels), (test_images, test_lebels)= fashion.load_data()
# first of all we need to normalize the images. So that all pixel values range between 0 to 1
train_images= train_images/255.0
test_images= test_images/255.0
train_images[0]
train_images[0].shape
# then we need to reshape the data or the images
train_images= train_images.reshape (len(train_images), 28,28,1)
test_images= test_images.reshape (len(test_images), 28,28,1)
def build_model (hp):
model= keras.Sequential([
keras.layers.Conv2D(filters=hp.Int ('conv_1_filter', min_value=32, max_value=128, step=16),
kernel_size=hp.Choice ('conv_1_kernel',values=[3,5]),
activation='relu', input_shape=(28,28,1)
),
keras.layers.Conv2D (filters=hp.Int ('conv_2_filter', min_value=32, max_value=128, step=16),
kernel_size= hp.Choice ('conv_2_kernel', values=[3,5]),
activation='relu'),
keras.layers.Flatten () ,
keras.layers.Dense (units= hp.Int ('dense_1_units', min_value=32, max_value=128, step=16),
activation='relu'),
keras.layers.Dense (10, activation='softmax')
])
model.compile (optimizer=keras.optimizers.Adam (hp.Choice ('learning_rate', values=[1e-2, 1e-3])), loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
from kerastuner import RandomSearch
from kerastuner.engine.hyperparameters import HyperParameters
tuner_search= RandomSearch (build_model, objective='val_accuracy', max_trials=5, directory='output', project_name='mnist_fashion')
tuner_search.search (train_images, train_lebels, epochs=3, validation_split=0.1)
# getting best model
model= tuner_search.get_best_models (num_models=1)[0]
model.summary ()
model.fit (train_images, train_lebels, epochs=10, validation_split=0.1, initial_epoch=3)
model.evaluate(test_images, test_lebels)
test_lebels[0]