如果对矩阵的知识有点遗忘,有点陌生,有点想不起来,请先看看这个网页:
http://blog.csdn.net/caimouse/article/details/55001181
基础知识已经补过了,就直接来使用TF的矩阵乘法了。
对矩阵a和矩阵b进行乘法,也就是a * b。两个参数输入必须是矩阵形式(张量的行列大于2),符合矩阵乘法的前后矩阵行列形式,包括转置之后。两个矩阵必须具有相同的数据类型,支持的数据类型:float16, float32, float64, int32, complex64, complex128。
也可以通过参数 transpose_a或transpose_b来设置矩阵在乘法之前进行转置,这时这些标志位应该设置为True,默认是False。
如果知道某一个矩阵有比较多0元素存在,也就是说存在稀疏矩阵,这时候可以通过设置参数a_is_sparse 或 b_is_sparse标志为True,这样可以大大优化矩阵的乘法计算。但张量的形式必须为2,数据类型为 float16 or float32。
例子:
#python 3.5.3 #2017-03-09 蔡军生 http://blog.csdn.net/caimouse # import tensorflow as tf import numpy as np a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) c = tf.matmul(a, b) print(a) print(b) print(c) # 在运行图计算之前,先初始化全局变量. init = tf.global_variables_initializer() # 准备会话来运行图. with tf.Session() as sess: sess.run(init) print('a=', a.eval()) print('b=', b.eval()) print('c=', c.eval()) print('\n\n3-D') #三维张量 a = tf.constant(np.arange(1,13), shape=[2, 2, 3]) b = tf.constant(np.arange(13,25), shape=[2, 3, 2]) c = tf.matmul(a, b) # 准备会话来运行图. with tf.Session() as sess: sess.run(init) print('a=', a.eval()) print('b=', b.eval()) print('c=', c.eval()) 结果输出如下:============== RESTART: D:/work/csdn/tensorflow/MNIST/matmul.py ==============Tensor("Const:0", shape=(2, 3), dtype=int32)Tensor("Const_1:0", shape=(3, 2), dtype=int32)Tensor("MatMul:0", shape=(2, 2), dtype=int32)a= [[1 2 3] [4 5 6]]b= [[ 7 8] [ 9 10] [11 12]]c= [[ 58 64] [139 154]]3-Da= [[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]]]b= [[[13 14] [15 16] [17 18]] [[19 20] [21 22] [23 24]]]c= [[[ 94 100] [229 244]] [[508 532] [697 730]]]>>>
