(tensorflow之十二)tensorflow与numpy函数的选择(以reshape为例)

tensorflow与numpy均提供了强大的矩阵运算功能,很多矩阵的运算函数功能是重复的。

那什么时候选择用tensorflow,什么时候选择用numpy呢?

这个的选择需正确的理解tensorflow与numpy计算过程的区别。

tensorflow的计算一般可分成两个阶段:

  • 第一阶段,定义所有的计算过程,即计算流图。在这个阶段,所有的变量均无实际参数值,仅仅表示一个计算过程;
  • 第二阶段,执行运算,创建会话(Session),此时才会对变量进行赋值;

而numpy的计算,会直接对具体的参数值进行运算。

因此,在tensoflow的第一阶段,表示计算过程时,必段选用tensorflow的函数;而在第二阶段,或者对已有具体参数值进行运算时,则需选择numpy。

具体可参考示意如下(以reshape函数为例):

import tensorflow as tf
import numpy as np
#矩阵a已经具有实际参数值,需选用numpy的reshape函数
a = [[3.0,2.0,1.0],[3.0,4.0,5.0],[7.0,8.0,9.0]]
b = np.reshape(a,[9])
#矩阵c是张量,在执行sess.run()无实际参数值,需选用tensorflow的reshape函数
c = tf.get_variable('c',[3,3],tf.float32,initializer=tf.truncated_normal_initializer(stddev=0.1))
d = tf.reshape(c,[9])

with tf.Session() as sess:
    tf.initialize_all_variables().run()
    print('the a is')
    print(a)
    print('the b is')
    print(b)
    print('the c is')
    print(sess.run(c))
    print('the d is')
    print(sess.run(d))
    print('the e is')
	#在执行sess.run(c)时,sess.run(c)已经具有实际参数值,则需选用numpy的reshape函数
    e = np.reshape(sess.run(c),[9])
    print(e)
运行结果如下:

the a is
[[3.0, 2.0, 1.0], [3.0, 4.0, 5.0], [7.0, 8.0, 9.0]]
the b is
[ 3.  2.  1.  3.  4.  5.  7.  8.  9.]
the c is
[[ 0.02078418  0.08195087  0.05464306]
 [-0.05831626 -0.11729162  0.14623356]
 [ 0.0392873  -0.04524051 -0.09136122]]
the d is
[ 0.02078418  0.08195087  0.05464306 -0.05831626 -0.11729162  0.14623356
  0.0392873  -0.04524051 -0.09136122]
the e is
[ 0.02078418  0.08195087  0.05464306 -0.05831626 -0.11729162  0.14623356
  0.0392873  -0.04524051 -0.09136122]



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值