![]()
TensorFlow is an open-source machine learning and deep learning framework developed by Google. It allows developers to build, train, and deploy AI models efficiently. It supports both CPU and GPU acceleration, making it suitable for large-scale computations.
Key Features of TensorFlow
✔ High Performance – Supports parallel processing on GPUs.
✔ Flexibility – Works with deep learning, reinforcement learning, and traditional ML.
✔ Scalability – Can run on multiple devices (Cloud, Edge, Mobile).
✔ Pre-trained Models – Offers models like MobileNet, EfficientNet, and BERT.
Installing TensorFlow
pip install tensorflow
To check if TensorFlow is installed:
import tensorflow as tf
print(tf.__version__) # Output TensorFlow version
Step 1: Creating Tensors in TensorFlow
A tensor is a multi-dimensional array, similar to NumPy arrays.
import tensorflow as tf
# Create tensors
tensor1 = tf.constant(5) # Scalar tensor
tensor2 = tf.constant([1, 2, 3]) # Vector tensor
tensor3 = tf.constant([[1, 2], [3, 4]]) # Matrix tensor
print(tensor1)
print(tensor2)
print(tensor3)
Step 2: Building a Simple Neural Network
We’ll use Keras (TensorFlow’s high-level API) to create a basic neural network.
from tensorflow import keras
from tensorflow.keras import layers
# Define a sequential model
model = keras.Sequential([
layers.Dense(16, activation='relu', input_shape=(10,)), # Input layer
layers.Dense(8, activation='relu'), # Hidden layer
layers.Dense(1, activation='sigmoid') # Output layer (for binary classification)
])
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Display model summary
model.summary()
Step 3: Training the Model
We generate random training data to demonstrate model training.
import numpy as np
# Generate dummy data
X_train = np.random.rand(1000, 10)
Y_train = np.random.randint(0, 2, size=(1000, 1))
# Train the model
model.fit(X_train, Y_train, epochs=10, batch_size=32)
Step 4: Making Predictions
# Generate test data
X_test = np.random.rand(5, 10)
# Make predictions
predictions = model.predict(X_test)
print(predictions)
Step 5: Saving and Loading Models
Saving a Model
model.save("my_model.h5") # Save model in HDF5 format
Loading a Model
loaded_model = keras.models.load_model("my_model.h5")
TensorFlow Applications
✔ Image Recognition – Face detection, medical imaging
✔ Natural Language Processing – Chatbots, text analysis
✔ Time-Series Analysis – Stock price prediction
✔ Reinforcement Learning – AI game-playing
