09.05.2023 Views

pdfcoffee

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4

Congratulations! You have defined a deeper network. Let us run the code for

40 iterations reaching an accuracy of 82%! Let's add the remaining part of the

code for the sake of completeness. The first part is to load and normalize the data:

import tensorflow as tf

from tensorflow.keras import datasets, layers, models, regularizers,

optimizers

from tensorflow.keras.preprocessing.image import ImageDataGenerator

import numpy as np

EPOCHS=50

NUM_CLASSES = 10

def load_data():

(x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data()

x_train = x_train.astype('float32')

x_test = x_test.astype('float32')

# normalize

mean = np.mean(x_train,axis=(0,1,2,3))

std = np.std(x_train,axis=(0,1,2,3))

x_train = (x_train-mean)/(std+1e-7)

x_test = (x_test-mean)/(std+1e-7)

y_train = tf.keras.utils.to_categorical(y_train,NUM_CLASSES)

y_test = tf.keras.utils.to_categorical(y_test,NUM_CLASSES)

return x_train, y_train, x_test, y_test

Then we need to have a part to train the network:

(x_train, y_train, x_test, y_test) = load_data()

model = build_model()

model.compile(loss='categorical_crossentropy',

optimizer='RMSprop',

metrics=['accuracy'])

# train

batch_size = 64

model.fit(x_train, y_train, batch_size=batch_size,

epochs=EPOCHS, validation_data=(x_test,y_test))

score = model.evaluate(x_test, y_test, batch_size=batch_size)

print("\nTest score:", score[0])

print('Test accuracy:', score[1])

[ 127 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!