Start using TensorFlow in Google Colaboratory for coding TensorFlow

Posted by


In this tutorial, we will walk you through the process of getting started with TensorFlow in Google Colaboratory, an online environment that allows you to write and execute code in a Jupyter notebook-like interface. TensorFlow is a powerful open-source machine learning library developed by Google that is widely used for building and training neural networks.

Step 1: Setting up Google Colaboratory
First, you will need a Google account in order to use Google Colaboratory. If you don’t already have one, you can create one for free at https://accounts.google.com/signup.

Once you have a Google account, go to the Google Colaboratory website at https://colab.research.google.com/. You will be prompted to sign in with your Google account.

Step 2: Creating a new Colab notebook
After signing in, you will be taken to the Colab welcome screen. To create a new Colab notebook, click on the "New Notebook" button in the bottom right corner. This will open a new notebook in a new tab.

Step 3: Installing TensorFlow in Colab
By default, Colab comes with many popular Python libraries pre-installed, including TensorFlow. However, if you want to ensure that you are using the latest version of TensorFlow, you can install it using the following command:

!pip install tensorflow

You can run this command in a code cell in your Colab notebook by typing it in and then pressing Shift+Enter. This will install the TensorFlow library in your Colab environment.

Step 4: Importing TensorFlow
Once TensorFlow is installed, you can import it into your Colab notebook using the following command:

import tensorflow as tf

You can run this command in a code cell in your notebook to import the TensorFlow library and start using its functionalities.

Step 5: Building and training a simple neural network
Now that you have TensorFlow set up in Colab, you can start building and training neural networks. Let’s create a simple neural network that classifies handwritten digits using the popular MNIST dataset.

First, you will need to load the MNIST dataset and preprocess it. Here’s a sample code snippet to do this:

from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical

# Load the MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Preprocess the data
x_train = x_train.reshape((x_train.shape[0], 28, 28, 1))
x_test = x_test.reshape((x_test.shape[0], 28, 28, 1))
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

This code snippet loads the MNIST dataset, reshapes the input data, normalizes the pixel values, and one-hot encodes the target labels.

Next, you can build a simple convolutional neural network using TensorFlow’s Keras API. Here’s a sample code snippet to build a CNN model for the MNIST dataset:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense

# Build the CNN model
model = Sequential([
    Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
    MaxPooling2D((2, 2)),
    Flatten(),
    Dense(128, activation='relu'),
    Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

This code snippet defines a simple CNN model with a convolutional layer, a max pooling layer, a fully connected layer with 128 neurons, and a softmax output layer with 10 neurons (one for each digit class).

Finally, you can train the model on the MNIST dataset using the following code snippet:

model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test))

This code snippet trains the model for 5 epochs with a batch size of 32 and validates it on the test set.

Step 6: Running code cells and monitoring training progress
You can run code cells in your Colab notebook by clicking on the play button next to the code cell or by pressing Shift+Enter. You can also monitor the training progress of your model by examining the training and validation loss and accuracy metrics displayed during training.

Step 7: Saving and exporting your Colab notebook
Once you have completed training your model, you can save your Colab notebook by clicking on "File" in the top menu and selecting "Save a copy in Drive". This will save a copy of your notebook in your Google Drive account.

You can also download your Colab notebook as a .ipynb file by clicking on "File" in the top menu and selecting "Download .ipynb". This allows you to save your work locally or share it with others.

In this tutorial, we covered the basics of getting started with TensorFlow in Google Colaboratory. We walked you through setting up Colab, installing TensorFlow, importing the library, building and training a simple neural network, and monitoring training progress. Happy coding!

0 0 votes
Article Rating
24 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@itsgonzalits
1 month ago

So youre telling me on this video (Video 2) we learned how to check the version of tensorflow, and in the next (Video 3) we will train a neural network on cancer!? ok.

@itsgonzalits
1 month ago

Me at 2:15: "Welp.. that escalated quickly."

@peterharrington4777
1 month ago

In 2023 it is no longer necessary to install tensorflow-gpu, when you change the kernel try to import tensorflow and it will already be there.

@Jirayu.Kaewprateep
1 month ago

Thank you, I also see the CPU / GPU toggle in the course that is beneficial for training in a virtual environment. In the course sometimes I need to run locally and upload from my VSCode.

@mikolashweiss1990
1 month ago

reset all runtimes is no longer in the dropdown menu, and the stated command ` !pip install tensorflow-gpu ` will not execute, returning the error `error: subprocess-exited-with-error`

This tutorial is unusable, please remove this video

@ritwiksarkar9017
1 month ago

I have some problem in colab ….when i am using loop in notebook tab space not automatically detect.. pls help…

@aaronissemwana420
1 month ago

WOOOW!!! so accurate ….Thanks for this Video

@jacksonkaib5122
1 month ago

Thank you so much. This technology is advancing accessibility to nlp and the field of ml/ds as a whole  🤗

@ainli4125466
1 month ago

i don't see the option to reset runtime after installed tensor flow… any advice?

@mianala
1 month ago

Awesome, just Awesome!

@ecjonck
1 month ago

So nice – wowzers. Thanks, Colab team.

@manish_rawat07
1 month ago

Do we require to install tensorflow or tensorflow-gpu for each new notebook? or do we only have to install it once in a notebook?

@sisiramdreamzz1111
1 month ago

Could anyone plz type the whta is provided for the second conde after" print "

@omkargharat8391
1 month ago

there is no option like change runtime type

@geekyprogrammer4831
1 month ago

Tensorfow doesn't support M1 😭😭😭

@cwrcwr
1 month ago

Around 40s it says “…just click New and you will find Colaboratory on the More menu…”

This skips over a step I had to do: going to the More menu, selecting “Connect more apps”, finding Colab there, and “installing” it. Seems to basically connect to a Google account, and make Colab the default app for opening .ipynb files.

@yawenchang9326
1 month ago

Thanks for this presentation! I love it.

@alejandroriosrubio8348
1 month ago

Muy bueno el contenido

@ireister
1 month ago

thank youuuuuuu

@laisviana6295
1 month ago

Could someone help me? When changing to GPU, my Notebook Settings it does not show 'Runtime Type', only the 'Hardware Accelerator' one.