要创建张量,可以使用tf.constant()
函数。
tf.constant(value, dtype, name = "")
参数说明
value
: 定义张量的n维数组值,可选dtype
: 定义张量数据类型,例如:tf.string
: 字符串类型tf.float32
: 浮点类型tf.int16
: 整型
- “name”: 张量的名字,可选,默认:“Const_1:0”
示例
创建0维张量,即标量,一个数值。
import tensorflow as tf
## rank 0
# Default name
r1 = tf.constant(1, tf.int16)
print(r1)
输出
Tensor("Const:0", shape=(), dtype=int16)
"Const:0"
– 张量名称shape
– 张量形状dtype
– 张量数据类型
示例
创建命名张量。
import tensorflow as tf
# Named my_scalar
r2 = tf.constant(1, tf.int16, name = "my_scalar")
print(r2)
输出
Tensor("my_scalar:0", shape=(), dtype=int16)
张量对象由一个惟一的标签(名称)、一个维度(形状)和一个数据类型(dtype)定义。
可以指定数据类型来定义张量。
示例
指定数据类型来定义张量。
import tensorflow as tf
# Decimal
r1_decimal = tf.constant(1.12345, tf.float32)
print(r1_decimal)
# String
r1_string = tf.constant("Guru99", tf.string)
print(r1_string)
输出
Tensor("Const_1:0", shape=(), dtype=float32)
Tensor("Const_2:0", shape=(), dtype=string)
示例
创建1维张量,即向量/一维数组。
import tensorflow as tf
## Rank 1
r1_vector = tf.constant([1,3,5], tf.int16)
print(r1_vector)
r2_boolean = tf.constant([True, True, False], tf.bool)
print(r2_boolean)
输出
Tensor("Const_3:0", shape=(3,), dtype=int16)
Tensor("Const_4:0", shape=(3,), dtype=bool)
示例
创建2维张量,即矩阵/2维数组。
import tensorflow as tf
## Rank 2
r2_matrix = tf.constant([ [1, 2],
[3, 4] ],tf.int16)
print(r2_matrix)
输出
Tensor("Const_5:0", shape=(2, 2), dtype=int16)
示例
创建3维张量。
import tensorflow as tf
## Rank 3
r3_matrix = tf.constant([ [[1, 2],
[3, 4],
[5, 6]] ], tf.int16)
print(r3_matrix)
输出
Tensor("Const_6:0", shape=(1, 3, 2), dtype=int16)