TensorFlow
Python · Advanced Python & AI
Theory
TensorFlow is an open-source deep learning framework from Google for building and training neural networks. Its high-level API, Keras (tf.keras), lets you stack layers like building blocks. In the example, tf.keras.Sequential holds a Dense layer of 16 neurons with ReLU activation followed by a Dense output of 1 neuron - a small network for predicting a number. Each Dense neuron computes a weighted sum of its inputs plus a bias, and the activation adds non-linearity.
The workflow has clear steps. compile() chooses the optimizer (adam, which updates weights) and the loss (mse, mean squared error, for regression). fit(X, y, epochs=10) trains by repeatedly predicting, measuring the loss and adjusting weights through backpropagation. evaluate() scores test data and predict() makes new predictions. Trained models can be saved and served in production.
Why we use it
Neural networks learn complex patterns in images, text, audio and large tabular data that classic models struggle with. TensorFlow and Keras provide the layers, training loop and hardware acceleration (GPUs) ready-made.
When to use it
Use it for deep learning on large datasets or unstructured data such as images and text. For small or ordinary tabular problems, scikit-learn models are usually simpler, faster and just as accurate.
How it works
- Prepare scaled numeric X and y
- Define layers with tf.keras.Sequential([...])
- model.compile(optimizer='adam', loss='mse')
- model.fit(X_train, y_train, epochs=...)
- Validation loss still improving? Yes: Keep training or tune. No: Stop to avoid overfitting.
- model.evaluate() then model.predict()
Syntax
import tensorflow as tf
model = tf.keras.Sequential([...])Example
model = tf.keras.Sequential([
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Dense(1)
])
model.compile(optimizer='adam', loss='mse')Key points
- Backed by Google; keras is its high-level, beginner-friendly API
- Well suited for production deployment and large-scale training
- compile() sets the optimizer and loss before training
- An epoch is one full pass over the training data
- Scale inputs - neural networks train poorly on raw magnitudes