Machine Learning · TensorFlow
TensorFlow Basics Explained for Beginners
Quick summary — TensorFlow basics
TensorFlow basics come down to four ideas: tensors (multi-dimensional arrays of numbers), models built from layers using Keras, training with an optimiser that reduces a loss function, and evaluation on data the model has not seen. Learn these with small examples in Python and you can follow most beginner deep learning tutorials.
In this guide you will learn:
- Tensors — shapes, dtypes and basic operations.
- Keras models — layers, activations and model summary.
- Training — loss, optimiser, epochs and batches.
- A first project plan — with templates to track experiments.
- Interview basics — TensorFlow questions beginners get.
SECTION 01Tensors: the data TensorFlow works with
A tensor is just a container of numbers with a shape, like a NumPy array. Images, text and tables all become tensors before a model can use them, so understanding shapes is the first real skill. If you have used NumPy before, much of this will feel familiar, and you can convert between the two freely.
| Rank | Example | Shape example | Real use |
|---|---|---|---|
| 0 (scalar) | A single number | () | A loss value |
| 1 (vector) | A list of numbers | (4,) | One row of features |
| 2 (matrix) | A table | (32, 4) | A batch of 32 rows with 4 features |
| 3 or more | Stacked tables | (32, 28, 28) | A batch of 32 greyscale images |
import tensorflow as tf
a = tf.constant(5.0)
b = tf.constant([1.0, 2.0, 3.0])
c = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)
print(a.shape, b.shape, c.shape) # () (3,) (2, 2)
print(c.dtype) # <dtype: 'float32'>
print(tf.reduce_sum(c).numpy()) # 10.0
print(tf.matmul(c, c).numpy()) # [[ 7. 10.] [15. 22.]]
import numpy as np
import tensorflow as tf
arr = np.arange(12, dtype=np.float32)
t = tf.convert_to_tensor(arr)
print(tf.reshape(t, (3, 4)).shape) # (3, 4)
print(tf.reshape(t, (-1, 2)).shape) # (6, 2) -1 means 'work it out'
print(t.numpy()[:3]) # back to NumPy: [0. 1. 2.]
SECTION 02Building a model with Keras
Keras is TensorFlow's high-level API for building models. A model is a stack of layers; each layer transforms the data a little, and together they learn a mapping from inputs to outputs.
| Piece | What it does | Common choice | Beginner tip |
|---|---|---|---|
| Input | Declares the shape of one example | keras.Input(shape=(4,)) | Match it to your feature count |
| Dense layer | Fully connected neurons | layers.Dense(16, activation='relu') | Start small: 16 or 32 units |
| Output layer | Produces the prediction | Dense(1, 'sigmoid') or Dense(n, 'softmax') | Matches the problem type |
| Loss | Measures how wrong predictions are | binary_crossentropy, sparse_categorical_crossentropy, mse | Pick by task: binary, multi-class, regression |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
keras.Input(shape=(4,)),
layers.Dense(16, activation="relu"),
layers.Dense(8, activation="relu"),
layers.Dense(3, activation="softmax"), # 3 classes
])
model.compile(optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"])
model.summary()
Problem type Output layer Loss
Yes/No (binary) Dense(1, 'sigmoid') binary_crossentropy
One of many classes Dense(n, 'softmax') sparse_categorical_crossentropy (integer labels)
Predict a number Dense(1) (no activation) mse or mae
Getting this pairing right fixes many 'model won't learn' problems.
SECTION 03Training, evaluating and predicting
Training means showing the model data in batches, measuring the loss and nudging the weights to reduce it. You then check performance on test data the model never saw. The example below uses the small Iris flower dataset, which trains in seconds on any laptop, so you can repeat it many times while experimenting.
| Term | Meaning | Typical value | What to watch |
|---|---|---|---|
| Epoch | One full pass over the training data | 10 to 50 for small problems | Validation loss stops improving |
| Batch size | Examples processed before each update | 32 | Memory use and speed |
| Validation split | Part of training data held out for checking | 0.2 | Gap between training and validation accuracy |
| Overfitting | Model memorises training data | Training accuracy high, validation low | Use more data, dropout or early stopping |
# pip install tensorflow scikit-learn
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
scaler = StandardScaler().fit(X_train)
X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)
history = model.fit(X_train, y_train, epochs=50, batch_size=16,
validation_split=0.2, verbose=0)
loss, acc = model.evaluate(X_test, y_test, verbose=0)
print(f"test accuracy: {acc:.2f}")
import numpy as np
probs = model.predict(X_test[:3], verbose=0)
print(probs.round(2)) # probability for each class
print(np.argmax(probs, axis=1)) # predicted class ids
print(y_test[:3]) # true class ids
model.save("iris_model.keras")
# reload later:
# from tensorflow import keras
# model = keras.models.load_model("iris_model.keras")
SECTION 04First TensorFlow project templates
Use these templates to plan your first project and track experiments like a professional.
First TensorFlow Project Plan
Dataset: Iris or another small public dataset
Problem type: binary / multi-class / regression
Input shape: ______ Output: ______
Baseline: simple model from scikit-learn (e.g. logistic regression)
Keras model: 1-2 hidden Dense layers
Metric: accuracy / MAE
Goal: match or beat the baseline on test data
Write-up: what worked, what did not
Experiment Log
Run Layers Units Epochs Batch Val acc Test acc Notes
1 2 Dense 16,8 50 16 ____ ____ baseline
2 2 Dense 32,16 50 16 ____ ____
3 + Dropout 32,16 80 16 ____ ____
Change only one thing per run.
TensorFlow Basics Checklist
☐ Create tensors and read shape/dtype
☐ Convert between NumPy and tensors
☐ Build a Sequential model
☐ Pick output layer and loss correctly
☐ compile, fit, evaluate, predict
☐ Read a training history plot
☐ Spot overfitting
☐ Save and load a model
SECTION 05Tips for learning TensorFlow as a beginner
These habits make deep learning far less confusing:
- Learn NumPy first — tensors behave like arrays, so array skills transfer directly.
- Start with tabular data — small datasets train in seconds on a laptop.
- Always have a baseline — compare your neural network to a simple model.
- Change one thing at a time — otherwise you will not know what helped.
- Plot training history — loss and accuracy curves reveal overfitting quickly.
SECTION 06Interview Q&A — TensorFlow basics
Q1What is a tensor?
A multi-dimensional array of numbers with a shape and a data type. TensorFlow uses tensors to represent inputs, weights and outputs.
Q2What is the difference between TensorFlow and Keras?
TensorFlow is the full machine learning framework. Keras is its high-level API for building and training models with less code.
Q3What does an activation function do?
It adds non-linearity to a layer's output, letting the network learn complex patterns. ReLU is common in hidden layers.
Q4What is the difference between an epoch and a batch?
A batch is a small group of examples used for one weight update. An epoch is one full pass through all training examples.
Q5How do you detect overfitting?
Training accuracy keeps improving while validation accuracy stalls or drops. Plotting both curves shows the gap clearly.
SECTION 07Test yourself — TensorFlow basics quiz
Five questions. No sign-up.
0 / 5Pick an answer to see why it is right or wrong.
SECTION 08Frequently asked questions
What is TensorFlow used for?
TensorFlow is used to build and train machine learning models, especially neural networks, for tasks like image recognition, text classification and forecasting.
Is TensorFlow hard for beginners?
The basics are manageable if you know Python and NumPy. Keras makes building and training models much simpler.
Do I need maths to learn TensorFlow?
Basic algebra and an intuition for gradients help. You can start building models and learn the maths gradually.
TensorFlow or PyTorch — which should beginners learn?
Both are popular. Pick one, learn the concepts well, and switching later is easier because the ideas are the same.
Can I run TensorFlow without a GPU?
Yes. Small models and datasets run fine on a CPU. GPUs matter for large models and datasets.
SECTION 09Related reads
Classroom & online · Noida
Learn machine learning step by step
Our Machine Learning Training Course covers Python, NumPy, classic ML and deep learning with TensorFlow through guided projects.
Talk to a counsellor for current fees- Python and NumPy foundations
- ML and TensorFlow projects
- Mock interviews
- Weekday & weekend batches