Back to Study Material Python

TensorFlow

TensorFlow is Google's open-source deep learning framework. It is the backbone of large-scale machine learning at companies like Google, Airbnb, and Twitte...

TensorFlow

Deep Learning with TensorFlow

TensorFlow is Google's open-source deep learning framework. It is the backbone of large-scale machine learning at companies like Google, Airbnb, and Twitter. TensorFlow 2.x made the library far more user-friendly by adopting eager execution and making Keras the default high-level API.

Install with pip install tensorflow. For GPU support, ensure CUDA and cuDNN are installed, then use pip install tensorflow[and-cuda].

The fundamental data structure in TensorFlow is the tensor, a multi-dimensional array similar to a NumPy array but capable of running on GPUs and TPUs: import tensorflow as tf a = tf.constant([[1.0, 2.0], [3.0, 4.0]]) b = tf.matmul(a, tf.transpose(a)) print(b.numpy()) # convert to NumPy array

Building a neural network with TensorFlow's Keras API: from tensorflow import keras from tensorflow.keras import layers

model = keras.Sequential([ layers.Dense(128, activation='relu', input_shape=(X_train.shape[1],)), layers.Dropout(0.3), layers.Dense(64, activation='relu'), layers.Dense(1, activation='sigmoid') # binary classification ])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.2, callbacks=[keras.callbacks.EarlyStopping(patience=5)])

The history object stores training and validation loss and metrics per epoch, useful for diagnosing overfitting.

TensorFlow's Dataset API handles large data efficiently: dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)) dataset = dataset.shuffle(1000).batch(32).prefetch(tf.data.AUTOTUNE)

SavedModel format enables deployment: model.save('my_model') loaded = keras.models.load_model('my_model')

Practical tip: Use model.summary() to print the architecture and count total parameters. A model with too many parameters relative to training samples will overfit; add Dropout layers or reduce units to regularize.

Exam tip: TensorFlow graph execution (tf.function) traces Python functions into computation graphs for performance. Understanding this helps debug errors like "TypeError: An op outside of tf.function" in production code.