欢迎这位怪蜀黍来到《人工智能深度学习入门练习之(15)TensorFlow – 创建张量 - 大码王 - 博客园》

关闭页面特效

要创建张量,可以使用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)

 

 posted on   大码王  阅读(293)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具

成都

复制代码

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示