Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TensorFlow Core Concepts

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:


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:

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

]

]

)

print

(

f

"Shape (Shape): {tensor.shape}"

)

       

(2, 3)

print

(

f

"Data Type (Dtype): {tensor.dtype}"

)

   

int32

print

(

f

"Dimension (Rank): {tf.rank(tensor)}"

)

     

2

print

(

f

"Device (Device): {tensor.device}"

)

     

/job:localhost/replica:0/task:0/device:CPU:0

Key Property Explanations:

Shape: describes the size of each dimension

Data Type (Dtype): the type of data in the tensor

Dimension/Rank (Rank): the number of dimensions of the tensor

Device: the device location where the tensor is stored

The Significance of Tensors in Machine Learning

Data Representation:

Practical Examples:


Computational Graph (Computational Graph)

A computational graph is a graph structure that usesNodeandEdgeto represent mathematical operations:

Simple Example:



Computational graph for calculating z = (x + y) * w:



x ──┐

    ├─→ [+] ──→ [×] ──→ z

y ──┘         ├

w ────────────┘

Advantages of Computational Graphs

1. Automatic differentiation:

2. Optimization opportunities:

3. Visual debugging:

4. Distributed computing:

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

)

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

)

print

(

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:

  1. Construction Phase: define the computational graph but do not perform any computation
  2. Execution stage: run the graph in a session to obtain results

The Role of the Session:

3.2 Eager Execution in TensorFlow 2.x

TensorFlow 2.x enables eager execution by default, making TensorFlow more "Pythonic":

Features of Eager Execution:

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

print

(

f

"Result: {c}"

)

 

Result: 5.0

Values can be accessed directly

print

(

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):

Graph mode (suitable for production deployment):

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

print

(

scalar_const

)

 

tf.Tensor(3.14, shape=(), dtype=float32)

Uses of Constants:

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

]

)

)

print

(

f

"Initial weight:\n{weight}"

)

Modify the value of a variable

weight.

assign

(

tf.

ones

(

[

2

,

3

]

)

)

print

(

f

"Modified weight:\n{weight}"

)

Partial update

weight

[

0

,

0

]

.

assign

(

5.0

)

print

(

f

"After partial update:\n{weight}"

)

Key Features of Variables:

  1. State retention: maintain state during training
  2. Gradient tracking: gradients with respect to variables can be computed
  3. Optimizable: can be updated by optimization algorithms
  4. 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

)

)

 

Hidden layer

output

=

tf.

matmul

(

hidden

,

W2

)

Output layer

print

(

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

)

print

(

f

"When x=3, dy/dx = {gradient}"

)

 

Should be 2x + 2 = 8

How GradientTape works:

  1. Recording operations: tape records all operations within its context
  2. Building the reverse graph: creates a reverse computational graph for gradient computation
  3. 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

)

   

print

(

f

"Epoch {epoch}: Loss = {loss:.4f}"

)


Summary of core concepts

Concept relationship diagram

TensorFlow core concept relationships:

输入数据 (Tensor) ──→ 计算图 (Graph) ──→ 输出结果 (Tensor)

      ↑                    ↓

   常量/变量            前向传播

      ↑                    ↓

   参数存储 ←──── 梯度更新 ←──── 自动微分

                              ↑

                        GradientTape