tensorflow中张量tensor

在 TensorFlow 中,主要操作的对象是张量(tf.Tensor)。张量表示一个多维数组,可以执行各种操作以构建和修改计算图。以下是一些常见的 TensorFlow 张量操作:

1. 创建张量:

  • 使用 tf.constant 创建常量张量。

  • 使用 tf.Variable 创建可训练的变量张量。

    创建常量张量

    tensor_a = tf.constant([[1, 2, 3],
    [4, 5, 6]], dtype=tf.int32)

    创建变量张量

    variable_tensor = tf.Variable([1, 2, 3])

2. 数学运算:

  • 加法、减法、乘法、除法等数学运算。

    tensor_a = tf.constant([1, 2, 3])
    tensor_b = tf.constant([4, 5, 6])

    加法

    sum_tensor = tf.add(tensor_a, tensor_b)

    减法

    diff_tensor = tf.subtract(tensor_a, tensor_b)

    乘法

    product_tensor = tf.multiply(tensor_a, tensor_b)

    除法

    quotient_tensor = tf.divide(tensor_a, tensor_b)

3. 形状操作:

  • 获取张量的形状、改变形状等。

    tensor = tf.constant([[1, 2, 3],
    [4, 5, 6]])

    获取形状

    shape = tf.shape(tensor)

    改变形状

    reshaped_tensor = tf.reshape(tensor, shape=(3, 2))

4. 索引和切片:

  • 使用索引和切片操作获取张量的部分。

    tensor = tf.constant([[1, 2, 3],
    [4, 5, 6]])

    获取第一行

    first_row = tensor[0, :]

    获取第一列

    first_column = tensor[:, 0]

    切片操作

    sliced_tensor = tensor[:, 1:3]

5. 归约操作:

  • 对张量的元素进行归约操作,例如求和、平均值等。

    tensor = tf.constant([1, 2, 3, 4, 5])

    求和

    sum_result = tf.reduce_sum(tensor)

    求平均值

    mean_result = tf.reduce_mean(tensor)

参考:

https://www.tensorflow.org/api_docs/python/tf/Tensor

相关推荐
DisonTangor8 小时前
llama.cpp 新特性:决策模型
人工智能·开源·aigc
鲲穹AI种草8 小时前
AI 生成 PPT 工具怎么选?鲲穹 PPT 功能实测与横向对比
人工智能·powerpoint
AI技术新视界9 小时前
Strata 的工作原理
人工智能·推理引擎·本地ai
2501_926978339 小时前
给自指系统接一个外部锚 —— 一个关于「用 AI 观察自己」的方法
人工智能·经验分享·笔记·机器学习·ai写作
不悔哥9 小时前
小智AI聊天机器人:ESP32上的开源语音助手拆解
人工智能·机器人·开源
枯木◊靠推文躺平版9 小时前
2026 企业级 AI 办公平台选型指南:如何评估可落地的办公 AI 能力
大数据·人工智能
空奈qwq9 小时前
ANN 全连接神经网络进阶:从反向传播到完整实战
人工智能·深度学习·神经网络
Dawson Zhu9 小时前
《Agentic Design Patterns》第 4 章导读:反思(Reflection)
人工智能·语言模型·架构·aigc·agi
llqbzllll10 小时前
Spring AI 工具调用不是反射一下就结束:用 2.0.1 跑通失败恢复与调用上限
人工智能·后端
北冥有鱼被烹10 小时前
砷化镓与磷化铟:光模块的地基——从化学键到AI缺货潮的底层逻辑
人工智能·python