AI学习之路(19)TensorFlow里的矩阵乘法

    xiaoxiao2021-03-25  90

    如果对矩阵的知识有点遗忘,有点陌生,有点想不起来,请先看看这个网页:

    http://blog.csdn.net/caimouse/article/details/55001181

    基础知识已经补过了,就直接来使用TF的矩阵乘法了。

    tf.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和矩阵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]]]>>> 

    1. TensorFlow入门基本教程

    http://edu.csdn.net/course/detail/4369

    2. C++标准模板库从入门到精通 

    http://edu.csdn.net/course/detail/3324

    3.跟老菜鸟学C++

    http://edu.csdn.net/course/detail/2901

    4. 跟老菜鸟学python

    http://edu.csdn.net/course/detail/2592

    5. 在VC2015里学会使用tinyxml库

    http://edu.csdn.net/course/detail/2590

    6. 在Windows下SVN的版本管理与实战 

     http://edu.csdn.net/course/detail/2579

    7.Visual Studio 2015开发C++程序的基本使用 

    http://edu.csdn.net/course/detail/2570

    8.在VC2015里使用protobuf协议

    http://edu.csdn.net/course/detail/2582

    9.在VC2015里学会使用MySQL数据库

    http://edu.csdn.net/course/detail/2672

    转载请注明原文地址: https://ju.6miu.com/read-21749.html

    最新回复(0)