TensorFlow Core Concepts
The name TensorFlow comes from its core structures for processing data - tensors (Tensor) and computation flows (Flow).
TensorFlow is an end-to-end open-source machine learning platform whose core advantages are:
- Flexible computational graph model: supports both dynamic and static graph modes
- Cross-platform deployment capability: can run on CPU, GPU, TPU, and mobile devices
- Rich ecosystem: includes subprojects such as TensorFlow Lite (mobile) and TensorFlow.js (browser)
- Production-Ready: provides a complete toolchain from research to production
Core Concept Analysis
Tensor
A tensor is the most basic data structure in TensorFlow, which can be understood asMultidimensional Arraysa generalized concept of.
From a mathematical perspective, a tensor is a multilinear function that can be used to represent linear relationships among vectors, scalars, and other tensors.
Simple Analogy:
- Scalar (0-dimensional tensor): a number, such as
5 - Vector (1-dimensional tensor): a list of numbers, such as
[1, 2, 3, 4] - Matrix (2-dimensional tensor): a table of numbers, such as
[[1, 2], [3, 4]] - 3-Dimensional Tensor: a cube of numbers, such as a color image (height × width × color channels)
- Higher-Dimensional Tensors: for example, video data (time × height × width × color channels)
Key Properties of Tensors
Example
Example Tensor
import
tensorflow
as
tf
Create a 2x3 matrix tensor
tensor
=
tf.
constant
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
]
)
(
f
"Shape (Shape): {tensor.shape}"
)
(2, 3)
(
f
"Data Type (Dtype): {tensor.dtype}"
)
int32
(
f
"Dimension (Rank): {tf.rank(tensor)}"
)
2
(
f
"Device (Device): {tensor.device}"
)
/job:localhost/replica:0/task:0/device:CPU:0
Key Property Explanations:
Shape: describes the size of each dimension
(2, 3)represents a matrix with 2 rows and 3 columns(224, 224, 3)represents a 224×224 pixel RGB image
Data Type (Dtype): the type of data in the tensor
tf.float32: 32-bit floating point (most commonly used)tf.int32: 32-bit integertf.bool: booleantf.string: String
Dimension/Rank (Rank): the number of dimensions of the tensor
- Scalar: rank 0
- Vector: rank 1
- Matrix: rank 2
Device: the device location where the tensor is stored
- CPU:
/device:CPU:0 - GPU:
/device:GPU:0
The Significance of Tensors in Machine Learning
Data Representation:
- Input data: images, text, and audio can all be represented as tensors
- Model parameters: weights and biases are all tensors
- Intermediate results: all data during computation are tensors
- Output result: prediction results, loss values, etc.
Practical Examples:
- Image classification: input tensor shape
(batch_size, height, width, channels) - Text processing: input tensor shape
(batch_size, sequence_length) - Time series: input tensor shape
(batch_size, time_steps, features)
Computational Graph (Computational Graph)
A computational graph is a graph structure that usesNodeandEdgeto represent mathematical operations:
- Node: represents mathematical operations (addition, multiplication, activation functions, etc.)
- Edge: represents the paths along which data flows (tensors)
Simple Example:
Computational graph for calculating z = (x + y) * w:
x ──┐
├─→ [+] ──→ [×] ──→ z
y ──┘ ├
w ────────────┘

Advantages of Computational Graphs
1. Automatic differentiation:
- Gradients can be computed automatically, enabling backpropagation
- No need to manually derive complex gradient formulas
2. Optimization opportunities:
- Compile-time optimization: merge operations, eliminate redundancy
- Runtime optimization: memory reuse, parallel computation
3. Visual debugging:
- Use TensorBoard to visualize model structure
- Facilitate understanding and debugging of complex models
4. Distributed computing:
- Different parts of the graph can be assigned to different devices
- Supports distributed training across machines
Static Graph vs Dynamic Graph
TensorFlow 1.x (Static Graph):
Example
TensorFlow 1.x style (for understanding only, not recommended)
import
tensorflow.
compat
.
v1
as
tf
tf.
disable_v2_behavior
(
)
Define the computational graph
x
=
tf.
placeholder
(
tf.
float32
,
shape
=
[
None
,
784
]
)
W
=
tf.
Variable
(
tf.
random
.
normal
(
[
784
,
10
]
)
)
b
=
tf.
Variable
(
tf.
zeros
(
[
10
]
)
)
y
=
tf.
matmul
(
x
,
W
)
- b
Create a session and execute
with
tf.
Session
(
)
as
sess:
sess.
run
(
tf.
global_variables_initializer
(
)
)
result
=
sess.
run
(
y
,
feed_dict
=
{
x: input_data
}
)
TensorFlow 2.x (Dynamic Graph / Eager Execution):
Example
TensorFlow 2.x style (recommended)
import
tensorflow
as
tf
Execute operations directly
x
=
tf.
constant
(
[
[
1.0
,
2.0
,
3.0
]
]
)
W
=
tf.
Variable
(
tf.
random
.
normal
(
[
3
,
2
]
)
)
b
=
tf.
Variable
(
tf.
zeros
(
[
2
]
)
)
y
=
tf.
matmul
(
x
,
W
)
- b
(
y
)
Get results immediately
Session (Session) and Eager Execution (Eager Execution)
The Session Mechanism of TensorFlow 1.x
In TensorFlow 1.x, the construction and execution of computational graphs are separated:
Two-Stage Process:
- Construction Phase: define the computational graph but do not perform any computation
- Execution stage: run the graph in a session to obtain results
The Role of the Session:
- Manage the execution environment of the graph
- Allocate and manage resources (memory, devices)
- Provide the context for graph execution
3.2 Eager Execution in TensorFlow 2.x
TensorFlow 2.x enables eager execution by default, making TensorFlow more "Pythonic":
Features of Eager Execution:
- Immediate evaluation: operations are executed immediately after being defined
- Easy to debug: Python debugging tools can be used
- Intuitive programming: just like writing ordinary Python code
Comparison Example:
Example
TensorFlow 2.x - Eager Execution
import
tensorflow
as
tf
a
=
tf.
constant
(
2.0
)
b
=
tf.
constant
(
3.0
)
c
=
a + b
(
f
"Result: {c}"
)
Result: 5.0
Values can be accessed directly
(
f
"numpy value of c: {c.numpy()}"
)
numpy value of c: 5.0
Graph Mode vs Eager Execution Mode
Eager execution mode (default, suitable for development and debugging):
- Operations execute immediately
- Easy to debug and understand
- Slightly lower performance
Graph mode (suitable for production deployment):
- Build the complete computational graph in advance
- Better optimization opportunities
- Higher execution efficiency
Switch to graph mode:
Example
@
tf.
function
def
compute_function
(
x
,
y
)
:
return
x * y + x
This function will be compiled into a graph
result
=
compute_function
(
tf.
constant
(
2.0
)
,
tf.
constant
(
3.0
)
)
Variables (Variable) and Constants (Constant)
Constants (Constant)
A constant isImmutablea tensor that cannot be modified once created:
Example
Create a constant
scalar_const
=
tf.
constant
(
3.14
)
vector_const
=
tf.
constant
(
[
1
,
2
,
3
,
4
]
)
matrix_const
=
tf.
constant
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
The value of a constant cannot be changed
(
scalar_const
)
tf.Tensor(3.14, shape=(), dtype=float32)
Uses of Constants:
- Store hyperparameters (learning rate, batch size, etc.)
- Store configuration data that does not need training
- Serve as fixed values in computation
Variables (Variable)
A variable isMutablea tensor that is typically used to store model parameters:
Example
Create variables
weight
=
tf.
Variable
(
tf.
random
.
normal
(
[
2
,
3
]
)
)
bias
=
tf.
Variable
(
tf.
zeros
(
[
3
]
)
)
(
f
"Initial weight:\n{weight}"
)
Modify the value of a variable
weight.
assign
(
tf.
ones
(
[
2
,
3
]
)
)
(
f
"Modified weight:\n{weight}"
)
Partial update
weight
[
0
,
0
]
.
assign
(
5.0
)
(
f
"After partial update:\n{weight}"
)
Key Features of Variables:
- State retention: maintain state during training
- Gradient tracking: gradients with respect to variables can be computed
- Optimizable: can be updated by optimization algorithms
- Savable: can be saved to checkpoint files
Use Cases: Variables vs Constants
| Feature | Variables (Variable) | Constants (Constant) |
|---|---|---|
| Mutability | Modifiable | Not modifiable |
| Main Use | Model parameters (weights, biases) | Hyperparameters, input data |
| Gradient computation | Supported | Not supported |
| Memory Usage | Persistent storage | Temporary storage |
| Typical examples | W = tf.Variable(...) |
learning_rate = tf.constant(0.01) |
Data flow and automatic differentiation
Forward propagation
The process of data flowing from input nodes to output nodes in the computational graph:
Example
Simple forward propagation example
import
tensorflow
as
tf
Input data
x
=
tf.
constant
(
[
[
1.0
,
2.0
]
]
)
Model parameters
W1
=
tf.
Variable
(
tf.
random
.
normal
(
[
2
,
3
]
)
)
b1
=
tf.
Variable
(
tf.
zeros
(
[
3
]
)
)
W2
=
tf.
Variable
(
tf.
random
.
normal
(
[
3
,
1
]
)
)
b2
=
tf.
Variable
(
tf.
zeros
(
[
1
]
)
)
Forward propagation
hidden
=
tf.
nn
.
relu
(
tf.
matmul
(
x
,
W1
)
- b1
)
Hidden layer
output
=
tf.
matmul
(
hidden
,
W2
)
- b2
Output layer
(
f
"Final output: {output}"
)
Automatic Differentiation
TensorFlow uses GradientTape to record operations and automatically compute gradients:
Example
Automatic differentiation example
x
=
tf.
Variable
(
3.0
)
Recording operations with GradientTape
with
tf.
GradientTape
(
)
as
tape:
y
=
x**
2
2
*x +
1
y = x² + 2x + 1
Computing dy/dx
gradient
=
tape.
gradient
(
y
,
x
)
(
f
"When x=3, dy/dx = {gradient}"
)
Should be 2x + 2 = 8
How GradientTape works:
- Recording operations: tape records all operations within its context
- Building the reverse graph: creates a reverse computational graph for gradient computation
- Compute gradients: computes gradients using the chain rule
Integration of concepts in the training loop
Example
Complete training step example
import
tensorflow
as
tf
Model and data
model
=
tf.
keras
.
Sequential
(
[
tf.
keras
.
layers
.
Dense
(
10
,
activation
=
'relu'
)
,
tf.
keras
.
layers
.
Dense
(
1
)
]
)
x_train
=
tf.
random
.
normal
(
[
100
,
5
]
)
y_train
=
tf.
random
.
normal
(
[
100
,
1
]
)
optimizer
=
tf.
keras
.
optimizers
.
Adam
(
0.01
)
Training step
@
tf.
function
def
train_step
(
x
,
y
)
:
with
tf.
GradientTape
(
)
as
tape:
predictions
=
model
(
x
)
loss
=
tf.
keras
.
losses
.
mse
(
y
,
predictions
)
gradients
=
tape.
gradient
(
loss
,
model.
trainable_variables
)
optimizer.
apply_gradients
(
zip
(
gradients
,
model.
trainable_variables
)
)
return
loss
Executing training
for
epoch
in
range
(
10
)
:
loss
=
train_step
(
x_train
,
y_train
)
(
f
"Epoch {epoch}: Loss = {loss:.4f}"
)
Summary of core concepts
Concept relationship diagram
TensorFlow core concept relationships:
输入数据 (Tensor) ──→ 计算图 (Graph) ──→ 输出结果 (Tensor)
↑ ↓
常量/变量 前向传播
↑ ↓
参数存储 ←──── 梯度更新 ←──── 自动微分
↑
GradientTape
