03_基础的Tensor OP
发布日期:2025-06-18 09:21:18 浏览次数:9 分类:精选文章

本文共 2303 字,大约阅读时间需要 7 分钟。

基础的Tensor OP操作

1. 矩阵乘法和向量乘法

在TensorFlow中,明确区分矩阵乘法和向量乘法是操作的关键。矩阵乘法通常使用tf.matmul()函数,而向量乘法则直接对Tensor进行操作。

  • 矩阵乘法:使用tf.matmul(a, b)计算两个矩阵的乘积。例如:

    a = tf.constant([[1, 2], [1, 2]], shape=(2, 2))b = tf.constant([[3, 4], [5, 6]], shape=(2, 2))c = tf.matmul(a, b)print(c.numpy())

    输出结果为:

    [[13  20] [23  34]]
  • 向量乘法:直接对两个向量进行乘法操作。例如:

    a = tf.constant([1, 2], shape=(2,))b = tf.constant([3, 4], shape=(2,))d = a * bprint(d.numpy())

    输出结果为:

    [[3  4] [6  8]]

2. 均值和方差

  • 均值计算:使用tf.reduce_mean()函数来计算数据的平均值。例如:

    m = tf.constant([1, 2, 3, 4, 5])mean = tf.reduce_mean(m)print(mean.numpy())

    输出结果为:

    3
  • 方差计算:使用tf.math.squared_difference()函数来计算数据与均值的平方差的平均值。例如:

    x = tf.constant([1, 3, 5, 7, 9])y = tf.constant([1, 1, 1, 1, 1])r = tf.math.squared_difference(x, y)print(r.numpy())

    输出结果为:

    [ 0  4 16 36 64]

3. 随机数生成

  • 正态分布:使用tf.random.normal()函数来生成正态分布数据。例如:

    shape = (3, 2)rand1 = tf.random.normal(shape=shape, mean=0.0, stddev=2.0)print(rand1.numpy())

    输出结果为:

    [[-0.9260874  4.9333167] [-2.0966494  2.6556277] [ 1.8420827  1.7115388]]
  • 均匀分布:使用tf.random.uniform()函数来生成均匀分布数据。例如:

    shape = (2, 4)minval = 1maxval = 10rand2 = tf.random.uniform(shape=shape, minval=minval, maxval=maxval)print(rand2.numpy())

    输出结果为:

    [[4.1472673 1.3256727 5.5261173 1.2175164] [7.5022736 6.664027  7.76919   7.363538]]

4. 寻找极值

  • 极大值:使用tf.argmax()函数来找到数据中的最大值及其索引。例如:

    a = tf.constant([1, 3, 5, 2, 11, 0, 99])d = tf.argmax(a)print(d.numpy())

    输出结果为:

    6
  • 极小值:使用tf.argmin()函数来找到数据中的最小值及其索引。例如:

    e = tf.argmin(a)print(e.numpy())

    输出结果为:

    5

完整代码示例

import tensorflow as tf# 矩阵乘法示例a = tf.constant([[1, 2], [1, 2]], shape=(2, 2))b = tf.constant([[3, 4], [5, 6]], shape=(2, 2))c = tf.matmul(a, b)print(c.numpy())# 向量乘法示例a = tf.constant([1, 2], shape=(2,))b = tf.constant([3, 4], shape=(2,))d = a * bprint(d.numpy())# 均值计算示例m = tf.constant([1, 2, 3, 4, 5])mean = tf.reduce_mean(m)print(mean.numpy())# 方差计算示例x = tf.constant([1, 3, 5, 7, 9])y = tf.constant([1, 1, 1, 1, 1])r = tf.math.squared_difference(x, y)print(r.numpy())# 正态分布随机数生成示例shape = (3, 2)rand1 = tf.random.normal(shape=shape, mean=0.0, stddev=2.0)print(rand1.numpy())# 均匀分布随机数生成示例shape = (2, 4)minval = 1maxval = 10rand2 = tf.random.uniform(shape=shape, minval=minval, maxval=maxval)print(rand2.numpy())# 寻找极大值示例a = tf.constant([1, 3, 5, 2, 11, 0, 99])d = tf.argmax(a)print(d.numpy())# 寻找极小值示例e = tf.argmin(a)print(e.numpy())
上一篇:C/C++计算(a+b)c的值 2019年9月电子学会青少年软件编程(C/C++)等级考试一级真题答案解析
下一篇:02_理解Tensor

发表评论

最新留言

很好
[***.229.124.182]2026年05月26日 23时40分42秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章