关于tf.constant([1,2,3])与tf.constant([[1,2,3]])的区别及类型疑问
Difference Between
tf.constant([1,2,3]) and tf.constant([[1,2,3]]) Great question! Let's break this down clearly and correct a common misunderstanding in your query.
Core Differences: Rank (Dimension) and Shape
The two tensors differ entirely in their rank (number of dimensions) and shape:
tf.constant([1,2,3]):- This creates a 1-dimensional tensor (rank=1)—what we usually call a vector.
- Its shape is
(3,), meaning it has one single axis with 3 elements. Think of it as a straight list of values with no row/column structure. - To access elements: Use a single index, e.g.,
t1[0]returns1,t1[2]returns3.
tf.constant([[1,2,3]]):- This creates a 2-dimensional tensor (rank=2)—a matrix.
- Its shape is
(1, 3), meaning it has two axes: the first axis (rows) holds 1 element, and the second axis (columns) holds 3 elements. You can visualize this as a single row of 3 values. - To access elements: Use two indices, e.g.,
t2[0, 0]returns1,t2[0, 2]returns3.
Correcting Your Misunderstanding
You asked if tf.constant([1,2,3]) creates a scalar and the other creates an array—this isn't accurate:
- A scalar is a 0-dimensional tensor, like
tf.constant(5)(shape()). The[1,2,3]version is a 1D vector, not a scalar. - Both are TensorFlow tensors (multi-dimensional arrays at their core)—the only difference is their number of dimensions. There's no "scalar vs array" split here; both are array-like structures, just with different ranks.
In short: The extra set of square brackets adds an entire dimension, turning a 1D vector into a 2D single-row matrix.
内容的提问来源于stack exchange,提问作者David_tut
相关产品推荐
相关产品推荐

