Skip to content

How to use the free GPU from Google Colab

Introduction

Google Colab, its full name is “Google colaboratory”, as the name suggests, it’s a service provided by Google. The advantage of Colab is that it provides a free GPU. Although you can only use the time limit of 12 hours a day, and the model training too long will be considered to be dig in the cryptocurrency.

But overall, Colab is still a best platform for people to learn machine learning without your own GPU.

Colab is an online Python execution platform, and its underlying operations are very similar to the famous Jupyter notebook.

In Colab’s FAQ, it’s also explained:

I believe that friends who have used Jupyter notebook are certainly not familiar with the operating mode of Colab.

So, let’s take a look how I used Colab’s instructions for using “Use CNN to build a simple classifier to MNIST —— by Keras“.


Have a Google account

The most important thing to do with Colab is to have a Google Account! Most people in modern times already have it, because Google offers too many services, which is really convenient.

If you have no a Google account, I highly recommend signing up for one.


Using GPU

search “Google Colab” in internet, the Colab website always display in the first item.

Or you can go to this website: https://colab.research.google.com/notebooks/welcome.ipynb?hl=en

Click it, and it will show you follow screen.

Good! welcome to Google Colab !

Click File -> New Python3 notebook to create a new notbook, and paste some code:

# -*- coding: utf-8 -*-
import os
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras.utils import np_utils, plot_model
from keras.datasets import mnist
import matplotlib.pyplot as plt
import pandas as pd


# Mnist Dataset
(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
x_train = X_train.reshape(60000, 1, 28, 28)/255
x_test = X_test.reshape(10000, 1, 28, 28)/255
y_train = np_utils.to_categorical(Y_train)
y_test = np_utils.to_categorical(Y_test)

# Model Structure
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=3, input_shape=(1, 28, 28), activation='relu', padding='same'))
model.add(MaxPool2D(pool_size=2, data_format='channels_first'))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dense(10, activation='softmax'))
print(model.summary())

# Train
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10, batch_size=64, verbose=1)
# Test
loss, accuracy = model.evaluate(x_test, y_test)
print('Test:')
print('Loss: %s\nAccuracy: %s' % (loss, accuracy))

# Save model
model.save('./CNN_Mnist.h5')

# Load Model
model = load_model('./CNN_Mnist.h5')

# Display
def plot_img(n):
    plt.imshow(X_test[n], cmap='gray')
    plt.show()


def all_img_predict(model):
    print(model.summary())
    loss, accuracy = model.evaluate(x_test, y_test)
    print('Loss:', loss)
    print('Accuracy:', accuracy)
    predict = model.predict_classes(x_test)
    print(pd.crosstab(Y_test.reshape(-1), predict, rownames=['Label'], colnames=['predict']))


def one_img_predict(model, n):
    predict = model.predict_classes(x_test)
    print('Prediction:', predict[n])
    print('Answer:', Y_test[n])
    plot_img(n)


if __name__ == '__main__':
    all_img_predict(model)



But, wait, don’t execute it. We’d better adjust our runtime type to GPU.

Click Runtime -> Change Runtime Type -> switch “Harware accelerator” to be GPU. Save it, and you maybe connect to GPU.

Press ctrl + Enter to start to execute your program. With GPU enhancement of the GPU, MNIST should run very fast!

You can freely replace your quest and use this free GPU!

Leave a Reply