Lesson 56 of 60 · python
Deep Learning Foundations – TensorFlow Basics
Duration: 25 minutes
TensorFlow Basics
TensorFlow is an open‑source library for numerical computation and large‑scale machine learning. Keras, now integrated as tf.keras, provides a high‑level API.
Installing TensorFlow
pip install tensorflow
Hello World: a simple dense network
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Define a simple sequential model
model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(10,)),
layers.Dense(1, activation='linear')
])
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
print(model.summary())
Training workflow
# Dummy data
import numpy as np
X = np.random.rand(1000, 10)
y = X @ np.random.rand(10,1) + np.random.randn(1000,1)*0.1
history = model.fit(X, y, epochs=30, batch_size=32, validation_split=0.2)
Visualizing training curves
import matplotlib.pyplot as plt
plt.plot(history.history['loss'], label='train loss')
plt.plot(history.history['val_loss'], label='val loss')
plt.legend()
plt.title('Training & Validation Loss')
plt.show()
Saving and loading models
model.save('my_model.h5')
# later
loaded = keras.models.load_model('my_model.h5')
GPU acceleration (optional)
- Install
tensorflow-gpuor use the default TensorFlow (GPU support is built‑in for recent builds). - Verify with
tf.config.list_physical_devices('GPU').
Key concepts
- Tensors: N‑dimensional arrays (like NumPy, but GPU‑compatible).
- Eager execution (default) vs. graph execution.
- Layers: building blocks (
Dense,Conv2D,LSTM, …). - Model subclassing for custom architectures.