1.tf.multiply()函数:矩阵对应元素相乘
官网定义:
multiply(x,y,name=None)
参数:
x: 一个类型为:half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128的张量。
y: 一个类型跟张量x相同的张量。
注意:
(1)该函数实现的是元素级别的相乘,也就是两个相乘的数元素各自相乘,而不是矩阵乘法
(2)两个相乘的数必须是相同的类型,否则会报错。
举例说明:
import tensorflow as tf # 1.数和矩阵相乘
x = tf.constant([[1,2,3],[2,3,4],[3,4,5]])
y1 = tf.constant(2)
xy1 = tf.multiply(x,y1) # 2.两个矩阵对应元素相乘
x = tf.constant([[1,2,3],[2,3,4],[3,4,5]])
y2 = tf.constant([[1,1,1],[2,2,2],[3,3,3]])
xy2 = tf.multiply(x,y2) # 3.元素类型不一样,报错
# x = tf.constant([[1,2,3],[2,3,4],[3,4,5]])
# y3 = tf.constant([[1.0,1.0,1.0],[2.0,2.0,2.0],[3.0,3.0,3.0]])
# xy3 = tf.multiply(x,y3) with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) print('xy1 =\n',sess.run(xy1))
print('xy2 =\n',sess.run(xy2))
# print('xy3 =\n',sess.run(xy3))
运行结果:
xy1 =
[[ 2 4 6]
[ 4 6 8]
[ 6 8 10]]
xy2 =
[[ 1 2 3]
[ 4 6 8]
[ 9 12 15]]
2.tf.matmul()函数:矩阵乘法
官网定义:
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会被处理为稀疏矩阵。
返回值: 一个跟张量a和张量b类型一样的张量且最内部矩阵是a和b中的相应矩阵的乘积。
举例说明:
import tensorflow as tf x = tf.constant([[1,2,3],
[2,3,4],
[3,4,5]])
y = tf.constant([[1,2,3],
[1,2,3],
[1,2,3]])
xy = tf.matmul(x,y) with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print('xy1 =\n',sess.run(xy))
运行结果:
xy =
[[ 6 12 18]
[ 9 18 27]
[12 24 36]]
3.multiply()和matmul()对比
举例说明:
import tensorflow as tf x = tf.constant([[1,2,3],
[2,3,4],
[3,4,5]])
y1 = tf.constant([[1,2,3],
[1,2,3],
[1,2,3]])
y2 = tf.constant([[1,2,3],
[1,2,3],
[1,2,3]])
z1 = tf.multiply(x,y1) # 对应元素相乘
z2 = tf.matmul(x,y2) # 矩阵相乘 with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print('z1 =\n',sess.run(z1))
print('z2 =\n',sess.run(z2))
运行结果:
z1 =
[[ 1 4 9]
[ 2 6 12]
[ 3 8 15]]
z2 =
[[ 6 12 18]
[ 9 18 27]
[12 24 36]]