Python convolutional neural network exercise

USE Jupyter Notebook

NB: Please only do Tasks 1-2

We will combine what we’ve learned about convolution, max-pooling and feed-forward layers, to build a ConvNet classifier for images.

Given Code:

in[]from __future__ import absolute_import, division, print_function

# Prerequisits
!pip install pydot_ng
!pip install graphviz
!apt install graphviz > /dev/null

# import statements
import tensorflow as tf
import tensorflow.contrib.eager as tfe
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
%matplotlib inline

# Enable the interactive TensorFlow interface, which is easier to understand as a beginner.
try:
tf.enable_eager_execution()
print(‘Running in Eager mode.’)
except ValueError:
print(‘Already running in Eager mode’)

in[]cifar = tf.keras.datasets.cifar10
(train_images, train_labels), (test_images, test_labels) = cifar.load_data()
cifar_labels = [‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’]

in[]# Take the last 10000 images from the training set to form a validation set
train_labels = train_labels.squeeze()
validation_images = train_images[-10000:, :, :]
validation_labels = train_labels[-10000:]
train_images = train_images[:-10000, :, :]
train_labels = train_labels[:-10000]

in[]print(‘train_images.shape = {}, data-type = {}’.format(train_images.shape, train_images.dtype))
print(‘train_labels.shape = {}, data-type = {}’.format(train_labels.shape, train_labels.dtype))

print(‘validation_images.shape = {}, data-type = {}’.format(validation_images.shape, validation_images.dtype))
print(‘validation_labels.shape = {}, data-type = {}’.format(validation_labels.shape, validation_labels.dtype))

in[]plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(‘off’)

in[]# Define the convolutinal part of the model architecture using Keras Layers.
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=48, kernel_size=(3, 3), activation=tf.nn.relu, input_shape=(32, 32, 3), padding=’same’),
tf.keras.layers.MaxPooling2D(pool_size=(3, 3)),
tf.keras.layers.Conv2D(filters=128, kernel_size=(3, 3), activation=tf.nn.relu, padding=’same’),
tf.keras.layers.MaxPooling2D(pool_size=(3, 3)),
tf.keras.layers.Conv2D(filters=192, kernel_size=(3, 3), activation=tf.nn.relu, padding=’same’),
tf.keras.layers.Conv2D(filters=192, kernel_size=(3, 3), activation=tf.nn.relu, padding=’same’),
tf.keras.layers.Conv2D(filters=128, kernel_size=(3, 3), activation=tf.nn.relu, padding=’same’),
tf.keras.layers.MaxPooling2D(pool_size=(3, 3)),

in[]model.summary()

in[]model.add(tf.keras.layers.Flatten()) # Flatten “squeezes” a 3-D volume down into a single vector.
model.add(tf.keras.layers.Dense(1024, activation=tf.nn.relu))
model.add(tf.keras.layers.Dropout(rate=0.5))
model.add(tf.keras.layers.Dense(1024, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

in[]tf.keras.utils.plot_model(model, to_file=”small_lenet.png”, show_shapes=True, show_layer_names=True)
display.display(display.Image(‘small_lenet.png’))

in[]batch_size = 128
num_epochs = 10 # The number of epochs (full passes through the data) to train for

# Compiling the model adds a loss function, optimiser and metrics to track during training
model.compile(optimizer=tf.train.AdamOptimizer(),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=[‘accuracy’])

# The fit function allows you to fit the compiled model to some training data
model.fit(x=train_images,
y=train_labels,
batch_size=batch_size,
epochs=num_epochs,
validation_data=(validation_images, validation_labels.astype(np.float32)))

print(‘Training complete’)

in[]metric_values = model.evaluate(x=test_images, y=test_labels)

print(‘Final TEST performance’)
for metric_value, metric_name in zip(metric_values, model.metrics_names):
print(‘{}: {}’.format(metric_name, metric_value))

in[]img_indices = np.random.randint(0, len(test_images), size=[25])
sample_test_images = test_images[img_indices]
sample_test_labels = [cifar_labels[i] for i in test_labels[img_indices].squeeze()]

predictions = model.predict(sample_test_images)
max_prediction = np.argmax(predictions, axis=1)
prediction_probs = np.max(predictions, axis=1)

in[]plt.figure(figsize=(10,10))
for i, (img, prediction, prob, true_label) in enumerate(
zip(sample_test_images, max_prediction, prediction_probs, sample_test_labels)):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(‘off’)

plt.imshow(img)
plt.xlabel(‘{} ({:0.3f})’.format(cifar_labels[prediction], prob))
plt.ylabel(‘{}’.format(true_label))

NB: Please only do Tasks 1-2

Tensorflow documentation: from ‘tensorflow.org’ website: search: tf.keras.layers.BatchNormalization’

research paper: search on web: ‘proceedings.mlr.press/v37/ioffe15.pdf’

Your Tasks 1. Experiment with the network architecture, try changing the numbers, types and sizes of layers, the sizes of fil

NB: Please only do Tasks 1-2

Get 20% Discount on This Paper
Pages (550 words)
Approximate price: -

Try it now!

Get 20% Discount on This Paper

We'll send you the first draft for approval by at
Total price:
$0.00

How it works?

Follow these simple steps to get your paper done

Place your order

Fill in the order form and provide all details of your assignment.

Proceed with the payment

Choose the payment system that suits you most.

Receive the final file

Once your paper is ready, we will email it to you.

Our Services

Custom Writings Help is a Quality-Oriented Company in Online Writing as a result of hiring exceptional professionals to execute clients' tasks.

Essays

Research Papers

At Custom Writings Help,We understand the struggle of research paper writing, and that is why at Custom WritingS Help, we are all out to help you. We pride ourselves on having a team of clinical writers. The stringent and rigorous vetting process ensures that only the 'BEST' Writers are chosen for the job. We have highly qualified Ph.D. and MA writers working with us; we equally offer these experienced writers specific bonuses and incentives to make them deliver highly original, unique, and informative content at reasonably low prices.

Admissions

Thesis Writing Service

Worlwide, Many Masters Students are struggling with Thesis Completion. A thesis is likely to be the longest and most challenging piece of work a student has ever completed. However, unlike essays and other assignments, a student can pick a particular interest topic and work on their initiative. Fortunately, we are there for you. At Custom Writings Help, you are assured of an authentic, imaginative, informative, linguistically great, and advantageous thesis that adheres to all your needs. So, why continue considering different writers when you have discovered the best in the field?

Editing

Custom Papers

Not a single student can avoid writing custom papers. However, a total lack of experience, skills, and time makes it very hard to produce a superb writing piece. Therefore, if you are seeking professional help, turn to us. Our specialized and experienced writers compose a variety of model papers, including custom essays, college term papers, research papers, book reports, MBA essays, executive summaries, dissertations, Ph.D. theses, admission essays, and research proposals for college and university students at any level.

Coursework

Essay Writing

Most of the students disregard the critical principles of essay writing and compose papers below sensible guidelines. Therefore, with Custom Writings Help, one should not worry about his/her essay. Our Writers compose informative and engaging content on all complexities and topics. We write meaningful and smart essays while prioritizing all aspects that bring about a good grade, such as impeccable grammar, proper structure, zero-plagiarism, and conformance to guidelines.

Coursework

Coourse Work Writing

Don't let the seemingly never-ending onslaught of writing assignments get you down. If you are looking where to get course work assistance online, the writers at Custom Writings Help are here to assist you with all of your writing needs. We undertake to unique delivery of papers that meet the professor's requirements. The content is proofread, edited, and checked plagiarism before submission to customers. No matter how big or small your work is, we will deliver on time. Try US Now! !

Coursework

Dissertation Writing Service

High-Quality Dissertation Writing Services are rare. They require Ph.D. academicians – not easily found. However, are an exception. The years, time, and resources we have invested in the dissertation world has given us a competitive advantage over others. Choose to come to Custom Writings Help; You will find perfect Ph.D. consultants who have written hundreds of dissertations theses ready to help you. Let our dissertation-writing services help you craft your dissertation, for you are assured we will give you the results.

× How can I help you?