On this page
article
TensorFlow Basics
Get started with TensorFlow — tensors, Keras API, building neural networks, training, and evaluation.
TensorFlow is Google’s open-source deep learning framework. Its high-level Keras API makes building neural networks accessible while retaining production-grade performance.
Installation
pip install tensorflow
Verify GPU support (optional):
import tensorflow as tf
print("GPUs:", tf.config.list_physical_devices('GPU'))
print("TF version:", tf.__version__)
Tensors — The Foundation
import tensorflow as tf
# Create tensors
scalar = tf.constant(42)
vector = tf.constant([1.0, 2.0, 3.0])
matrix = tf.constant([[1, 2], [3, 4]])
# Operations
a = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)
b = tf.constant([[5, 6], [7, 8]], dtype=tf.float32)
print(tf.matmul(a, b))
print(tf.reduce_sum(a))
Build a Neural Network with Keras
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Dense(128, activation='relu', input_shape=(784,)),
layers.Dropout(0.2),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax'),
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
)
model.summary()
Train on MNIST
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
x_test = x_test.reshape(-1, 784).astype('float32') / 255.0
history = model.fit(
x_train, y_train,
epochs=10,
batch_size=128,
validation_split=0.1,
verbose=1,
)
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"Test accuracy: {test_acc:.4f}")
Functional API — Complex Architectures
inputs = keras.Input(shape=(784,))
x = layers.Dense(128, activation='relu')(inputs)
x = layers.Dropout(0.2)(x)
x = layers.Dense(64, activation='relu')(x)
outputs = layers.Dense(10, activation='softmax')(x)
model = keras.Model(inputs=inputs, outputs=outputs)
Callbacks
callbacks = [
keras.callbacks.EarlyStopping(patience=3, restore_best_weights=True),
keras.callbacks.ModelCheckpoint('best_model.keras', save_best_only=True),
keras.callbacks.TensorBoard(log_dir='./logs'),
]
model.fit(x_train, y_train, epochs=50, callbacks=callbacks)
Save and Load Models
model.save('my_model.keras')
loaded = keras.models.load_model('my_model.keras')
predictions = loaded.predict(x_test[:5])
Transfer Learning
base_model = keras.applications.MobileNetV2(
input_shape=(224, 224, 3),
include_top=False,
weights='imagenet',
)
base_model.trainable = False
inputs = keras.Input(shape=(224, 224, 3))
x = base_model(inputs, training=False)
x = layers.GlobalAveragePooling2D()(x)
outputs = layers.Dense(10, activation='softmax')(x)
model = keras.Model(inputs, outputs)
TensorFlow scales from research notebooks to production serving with TensorFlow Serving and TensorFlow Lite.