TensorFlow Tutorial for Beginners
TensorFlow is an open-source machine learning framework used to build, train, evaluate, and deploy models. It is widely used for neural networks, deep learning, computer vision, natural language processing, time-series prediction, and production machine learning workflows.
This TensorFlow tutorial introduces the core ideas in a practical order: installing TensorFlow, creating tensors, building a small neural network with Keras, training the model, checking accuracy, saving the model, and understanding the parts of a TensorFlow project.
For official learning paths and reference material, see the TensorFlow tutorials, the TensorFlow quickstart for beginners, and TensorFlow Learn.
What TensorFlow Is Used For in Machine Learning
TensorFlow helps you express numerical computations as operations on tensors. A tensor is a multi-dimensional array of values. In machine learning, tensors commonly represent input data, model weights, labels, predictions, images, text embeddings, or batches of training examples.
In modern TensorFlow, most beginner and application-level model building is done with tf.keras. Keras provides a clear API for defining layers, compiling a model, training with data, and measuring performance. TensorFlow also includes lower-level tools for custom training loops, distributed training, data pipelines, model export, and deployment.
| TensorFlow concept | Meaning in a project |
|---|---|
| Tensor | Data stored as numbers with shape and data type |
| Layer | A reusable operation in a neural network, such as Dense or Conv2D |
| Model | A group of layers that maps inputs to predictions |
| Loss function | A value that tells how wrong the prediction is |
| Optimizer | An algorithm that updates model weights during training |
| Metric | A human-readable measurement such as accuracy |
Install TensorFlow and Verify Your Python Environment
TensorFlow is commonly installed in a Python virtual environment. The exact setup can vary by operating system and hardware, especially for GPU acceleration. For a beginner CPU-based setup, the following commands are enough in many environments.
python -m venv tf-env
source tf-env/bin/activate
python -m pip install --upgrade pip
pip install tensorflow
On Windows Command Prompt, the activation command is different:
tf-env\Scripts\activate
After installation, verify that TensorFlow imports correctly.
import tensorflow as tf
print(tf.__version__)
If the command prints a version number, TensorFlow is installed and ready to use. If the import fails, check the Python version, virtual environment, operating system support, and the installation instructions from TensorFlow documentation.
Create Tensors in TensorFlow
A tensor has a value, a shape, and a data type. Scalars, vectors, matrices, and higher-dimensional arrays are all tensors. TensorFlow operations can run on tensors directly.
import tensorflow as tf
scalar = tf.constant(10)
vector = tf.constant([1, 2, 3])
matrix = tf.constant([[1, 2], [3, 4]])
print(scalar)
print(vector.shape)
print(matrix.dtype)
TensorFlow Operations on Tensors
TensorFlow supports arithmetic, matrix operations, reshaping, slicing, type conversion, and many mathematical functions. These operations are the building blocks of machine learning models.
import tensorflow as tf
a = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[10, 20], [30, 40]])
sum_result = tf.add(a, b)
product_result = tf.matmul(a, b)
print(sum_result)
print(product_result)
tf.add() performs element-wise addition. tf.matmul() performs matrix multiplication. For neural networks, TensorFlow uses these types of operations internally while computing predictions and gradients.
Build a Simple TensorFlow Neural Network with Keras
The most common beginner workflow is to build a model with tf.keras.Sequential. A sequential model is useful when the model is a simple stack of layers where the output of one layer becomes the input of the next layer.
The following example uses the MNIST handwritten digit dataset. The goal is to classify grayscale images of digits from 0 to 9.
import tensorflow as tf
# Load sample data
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Normalize pixel values from 0-255 to 0-1
x_train = x_train / 255.0
x_test = x_test / 255.0
# Build the model
model = tf.keras.Sequential([
tf.keras.Input(shape=(28, 28)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dense(10)
])
# Configure training
model.compile(
optimizer="adam",
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=["accuracy"]
)
# Train the model
model.fit(x_train, y_train, epochs=5)
# Evaluate the model
test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=2)
print("Test accuracy:", test_accuracy)
Understand the TensorFlow Model Code
The MNIST model contains four main parts. Input declares the shape of each image. Flatten converts each 28 by 28 image into a one-dimensional vector. The hidden Dense layer learns useful combinations of pixel values. The final Dense(10) layer produces one score for each digit class.
The model is compiled with an optimizer, a loss function, and a metric. During training, TensorFlow calculates the loss, computes gradients, and updates the model weights. During evaluation, it uses the test data to estimate how well the model performs on examples it did not train on.
Convert TensorFlow Logits into Class Probabilities
The final layer in the previous model returns raw scores, also called logits. To convert logits into probabilities, add a softmax layer or wrap the trained model in another Keras model.
probability_model = tf.keras.Sequential([
model,
tf.keras.layers.Softmax()
])
predictions = probability_model.predict(x_test[:5])
print(predictions[0])
The output contains probability values for the 10 digit classes. The class with the highest probability is the model’s predicted digit.
Save and Load a TensorFlow Model
After training a model, save it so that it can be reused without retraining. TensorFlow models can be saved and loaded with Keras methods.
model.save("mnist_digit_model.keras")
loaded_model = tf.keras.models.load_model("mnist_digit_model.keras")
test_loss, test_accuracy = loaded_model.evaluate(x_test, y_test, verbose=0)
print("Loaded model accuracy:", test_accuracy)
Use tf.data for TensorFlow Input Pipelines
Small examples can pass NumPy arrays directly to model.fit(). Larger projects usually need input pipelines for batching, shuffling, preprocessing, and efficient loading. TensorFlow provides tf.data.Dataset for this purpose.
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_dataset = (
train_dataset
.shuffle(buffer_size=10000)
.batch(32)
.prefetch(tf.data.AUTOTUNE)
)
model.fit(train_dataset, epochs=3)
shuffle() changes the order of examples during training, batch() groups examples together, and prefetch() helps overlap data preparation with model execution.
Eager Execution and Graph Execution in TensorFlow
TensorFlow 2 executes operations eagerly by default, which means Python statements run immediately and are easier to debug. For performance-sensitive code, TensorFlow can convert Python functions into graph functions with @tf.function.
import tensorflow as tf
@tf.function
def add_and_square(x, y):
total = x + y
return total * total
result = add_and_square(tf.constant(2), tf.constant(3))
print(result)
For beginners, it is usually better to start with normal eager code. Use @tf.function when you understand the code path and need TensorFlow to optimize repeated computations.
TensorFlow Project Workflow for Beginners
A basic TensorFlow project usually follows this workflow:
- Collect or load the dataset.
- Clean and preprocess the input data.
- Split data into training, validation, and test sets.
- Build the model with Keras layers.
- Compile the model with a loss function, optimizer, and metrics.
- Train the model with
model.fit(). - Evaluate the model on unseen test data.
- Save the trained model for later use.
- Monitor results and improve the model if needed.
Common TensorFlow Beginner Errors and Fixes
| Error or issue | Likely cause | Practical fix |
|---|---|---|
| Tensor shape mismatch | The model expects a different input shape | Print x.shape and check the first layer input shape |
| Loss does not decrease | Data is not normalized, labels are wrong, or learning rate is unsuitable | Normalize inputs, verify labels, and test a smaller model |
| Training accuracy high but test accuracy low | The model is overfitting | Add validation data, reduce model size, or use regularization |
| ImportError for TensorFlow | TensorFlow is not installed in the active Python environment | Activate the correct virtual environment and reinstall TensorFlow |
| GPU is not used | GPU support is not configured for the local system | Check official TensorFlow installation notes for your OS and hardware |
When to Use TensorFlow Instead of a Simpler Library
TensorFlow is suitable when you need neural networks, deep learning workflows, custom model architectures, large datasets, deployment options, or production-oriented model serving. If the task only needs simple tabular machine learning, a library such as scikit-learn may be easier to start with. TensorFlow is most useful when the problem benefits from tensors, gradients, layers, and model training at scale.
TensorFlow Tutorial Practice Exercises
After running the examples above, try these exercises to strengthen the basics:
- Change the number of hidden units from 128 to 64 and compare the test accuracy.
- Train the MNIST model for 1, 5, and 10 epochs and record the results.
- Add another
Densehidden layer and observe whether the model improves. - Use
model.summary()to inspect the number of trainable parameters. - Save the model, restart Python, load the model, and run evaluation again.
TensorFlow FAQ for Beginners
Is TensorFlow only used for deep learning?
No. TensorFlow is best known for deep learning, but it can also be used for numerical computation, preprocessing, custom training workflows, and model deployment. Most beginners use it for neural networks through Keras.
Do I need Keras to learn TensorFlow?
You do not strictly need Keras, but it is the recommended starting point for most beginners because it provides a simple API for layers, models, training, and evaluation.
What is the difference between a tensor and a NumPy array?
A NumPy array is a Python data structure for numerical computing. A TensorFlow tensor is similar in shape and values, but TensorFlow tensors can participate in TensorFlow operations, automatic differentiation, device placement, and model training.
Why does TensorFlow use epochs during model training?
An epoch means one complete pass through the training data. More epochs give the model more chances to learn, but too many epochs can cause overfitting if the model starts memorizing the training data instead of learning patterns.
Should a TensorFlow beginner start with CPU or GPU?
A CPU setup is enough for beginner tutorials and small datasets such as MNIST. A GPU becomes useful for larger models, image datasets, long training jobs, and experiments that need faster computation.
TensorFlow Tutorial Editorial QA Checklist
- Verify that every TensorFlow code block imports
tensorflow as tfbefore using TensorFlow APIs. - Check that installation commands are separated from Python examples and use the correct PrismJS language class.
- Confirm that model examples explain input shape, loss function, optimizer, metric, and evaluation.
- Ensure output-only snippets, if added later, use the
outputcode block class. - Review TensorFlow version-sensitive instructions against official TensorFlow documentation before making future updates.
TutorialKart.com