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

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

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-D
a= [[[ 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入门基本教程

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

3.跟老菜鸟学C++

4. 跟老菜鸟学python

5. 在VC2015里学会使用tinyxml库

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协议

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




  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

caimouse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值