tensorflow的乘法与转置: tf.multiply,tf.matmul和tf.transpose()

本文详细介绍了 TensorFlow 中用于元素乘法的 tf.multiply 函数,矩阵乘法的 tf.matmul 操作,以及如何进行张量转置的 tf.transpose 函数。tf.multiply 支持广播机制,执行元素级别的乘法;tf.matmul 处理矩阵的内积,可选择是否转置输入;tf.transpose 则用于交换张量的维度,实现转置效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tf.multiply:

函数原型:

tf.math.multiply(
    x,
    y,
    name=None
)

说明:

  • 作用:对应元素相乘,并且具有广播作用。
  • x: 类型为:half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128的张量。
  • y: 类型跟张量x相同的张量。
  • 返回:x * y(element-wise )

tf.matmul:

函数原型:

tf.linalg.matmul(
    a,
    b,
    transpose_a=False,
    transpose_b=False,
    adjoint_a=False,
    adjoint_b=False,
    a_is_sparse=False,
    b_is_sparse=False,
    name=None
)

说明:

  • 作用:最里面的矩阵相乘,两个输入必须时矩阵。
  • a: 类型为 float16, float32, float64, int32, complex64, complex128 且张量秩 > 1 的张量。
  • b: 类型跟张量a相同的张量。
  • transpose_a: 如果为真, a则在进行乘法计算前进行转置。
  • transpose_b: 如果为真, b则在进行乘法计算前进行转置。
  • adjoint_a: 如果为真, a则在进行乘法计算前进行共轭和转置。
  • adjoint_b: 如果为真, b则在进行乘法计算前进行共轭和转置。
  • a_is_sparse: 如果为真, a会被处理为稀疏矩阵。
  • b_is_sparse: 如果为真, b会被处理为稀疏矩阵。

例子:

import tensorflow as tf
a = tf.constant([[2, 3]])
a1 = tf.constant([2, 3])
b = tf.constant([[0, 1], [2, 3]])
x = tf.constant([[[0, 1], [2, 3], [1, 3]],
                 [[4, 5], [6, 7], [4, 7]]])
y = tf.constant([[[0, 1, 0], [2, 3, 1]], [[4, 5, 1], [6, 7, 2]]])
z=tf.matmul(y, x)#最里面矩阵相乘(要求一一对应,没有广播性)
c = tf.matmul(a, b)  # 矩阵乘法
d = tf.multiply(a, b)  # 对应相乘
e = tf.multiply(a1, b)  # 对应相乘
with tf.Session() as sess:
    print(sess.run(c))
    print(sess.run(d))
    print(sess.run(e))
    print(sess.run(z))

输出:
[[ 6 11]]
=======================
[[0 3]
 [4 9]]
 =======================
[[0 3]
 [4 9]]
 =======================
[[[ 2  3]
  [ 7 14]]
 [[50 62]
  [74 93]]]

tf.transpose():

函数原型:

tf.transpose(
    a,
    perm=None,
    name='transpose',
    conjugate=False
)

说明:

  • 这个函数主要适用于交换输入张量的不同维度,如果输入张量是二维,就相当是转置。
  • dimension_n是整数,如果张量是三维,就是用0,1,2来表示

例子:

import tensorflow as tf
b = tf.constant([[0, 1], [2, 3]])
c= tf.transpose(b, [1,0])
x = tf.constant([[[0, 1], [2, 3], [1, 3]],
                 [[4, 5], [6, 7], [4, 7]]])
y = tf.transpose(x, [2,0,1])
with tf.Session() as sess:
    print(sess.run(c))
    print(sess.run(y))

输出:
[[0 2]
 [1 3]]
 =====================
[[[0 2 1]
  [4 6 4]]
 [[1 3 3]
  [5 7 7]]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值