TensorFlow Basics

Loading

TensorFlow Basics: A Comprehensive Guide

Introduction to TensorFlow

TensorFlow is an open-source machine learning framework developed by Google for building and deploying machine learning (ML) and deep learning models. It provides flexibility, scalability, and high performance across various platforms, including CPUs, GPUs, and TPUs (Tensor Processing Units).

Why TensorFlow?

Ease of Use – Provides high-level APIs like Keras for quick development.
Scalability – Supports distributed training and deployment.
Flexible Deployment – Works on cloud, mobile, and embedded devices.
Computation Graphs – Efficient execution via graphs and eager execution.
GPU Acceleration – Optimized for deep learning workloads.


1. Installing TensorFlow

To get started, install TensorFlow in a Python environment:

Step 1: Create a Virtual Environment (Optional)

python -m venv tensorflow_env
source tensorflow_env/bin/activate   # On Mac/Linux
tensorflow_env\Scripts\activate      # On Windows

Step 2: Install TensorFlow

pip install tensorflow

Step 3: Verify Installation

import tensorflow as tf
print(tf.__version__)  # Should print the installed version

2. TensorFlow Core Concepts

TensorFlow operates on Tensors, which are multi-dimensional arrays similar to NumPy arrays. It uses computational graphs for efficient execution.

2.1 Creating Tensors

import tensorflow as tf

# Scalar (0D Tensor)
scalar = tf.constant(5)
print(scalar)

# Vector (1D Tensor)
vector = tf.constant([1, 2, 3])
print(vector)

# Matrix (2D Tensor)
matrix = tf.constant([[1, 2], [3, 4]])
print(matrix)

# 3D Tensor
tensor_3d = tf.constant([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(tensor_3d)

2.2 Tensor Operations

# Adding two tensors
a = tf.constant([1, 2, 3])
b = tf.constant([4, 5, 6])
c = a + b  # Element-wise addition
print(c)

# Multiplication
d = a * b
print(d)

# Dot Product
dot_product = tf.tensordot(a, b, axes=1)
print(dot_product)

3. Variables, Constants, and Placeholders

3.1 TensorFlow Constants

x = tf.constant(10)  # Immutable
print(x)

3.2 TensorFlow Variables

Unlike constants, variables can change during execution.

var = tf.Variable(10)
print(var.numpy())

var.assign(20)  # Update variable
print(var.numpy())

var.assign_add(5)  # Increment by 5
print(var.numpy())

4. TensorFlow Graphs & Eager Execution

4.1 Computational Graph

TensorFlow uses computational graphs to optimize execution.

# Define a computation
x = tf.constant(3.0)
y = tf.constant(4.0)
z = x * y + 2

# Execute in a session (only needed in TF 1.x)
print(z.numpy())  # Direct execution in TF 2.x

4.2 Eager Execution

TensorFlow 2.x runs computations eagerly (immediate execution), making debugging easier.

tf.executing_eagerly()  # Returns True by default in TF 2.x

5. Working with TensorFlow Datasets

5.1 Creating a Dataset

import tensorflow as tf

# Create a dataset from a list
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5])
for item in dataset:
    print(item.numpy())

5.2 Preprocessing Data

# Batch and Shuffle Data
dataset = dataset.shuffle(buffer_size=3).batch(2)
for batch in dataset:
    print(batch.numpy())

6. Building a Simple Neural Network

6.1 Import Required Libraries

import tensorflow as tf
from tensorflow import keras
import numpy as np

6.2 Load and Prepare the Dataset

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

# Normalize data
x_train, x_test = x_train / 255.0, x_test / 255.0

6.3 Define a Simple Neural Network Model

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),  # Flatten 2D image to 1D
    keras.layers.Dense(128, activation='relu'),  # Fully connected layer
    keras.layers.Dense(10, activation='softmax') # Output layer with 10 classes
])

6.4 Compile the Model

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

6.5 Train the Model

model.fit(x_train, y_train, epochs=5)

6.6 Evaluate the Model

test_loss, test_acc = model.evaluate(x_test, y_test)
print("Test Accuracy:", test_acc)

7. Saving and Loading Models

7.1 Save the Model

model.save("my_model.h5")

7.2 Load the Model

new_model = keras.models.load_model("my_model.h5")

8. TensorFlow for Deep Learning

8.1 Convolutional Neural Networks (CNNs)

model = keras.Sequential([
    keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
    keras.layers.MaxPooling2D(2,2),
    keras.layers.Conv2D(64, (3,3), activation='relu'),
    keras.layers.MaxPooling2D(2,2),
    keras.layers.Flatten(),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])

9. Deploying a TensorFlow Model with Flask

9.1 Create a Flask API

from flask import Flask, request, jsonify
import tensorflow as tf

app = Flask(__name__)
model = tf.keras.models.load_model("my_model.h5")

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    prediction = model.predict([data['input']])
    return jsonify({'prediction': prediction.tolist()})

if __name__ == '__main__':
    app.run(port=5000)

Leave a Reply

Your email address will not be published. Required fields are marked *