tensorflow学习总结(一)

在阅读论文时,论文中的模型是基于Tensorflow的,所以决定找一个Tensorflow的教程视频来填补一下空缺,本文作为Tensorflow课程的第一堂课的笔记。


课程链接:深度学习Tensorflow课程链接
也可参考中文教程:Tensorflow中文教程


一、基本概念

  • 使用图(graph)来表示计算任务
  • 在Session(会话)的上下文中执行图
  • 用Tensor表示数据
  • 通过变量(Variable)来维护状态
  • 用Feed和Fetch可以为任意的操作赋值或者从其中获取数据

在这里插入图片描述

二、Tensorflow的执行过程

以一下代码为例:

#tensorflow执行过程
m1 = tf.xonstant([[3, 3]])
m2 = tf.constant([[2, 2]])

#创建矩阵乘法
product = tf.subtract(m1, m2)
print(product)   

若此时输出product,在正常的逻辑来说会输出[1,1],但是在Tensorflow中,会输出如下: Tensor("MatMul:0", shape=(1, 1), dtype=int32)即输出了Tensor这个张量,而不是理想的值。应该在会话中输出Tensor的值,正确的写法应该是这样:

m1 = tf.constant([[3, 3]])
m2 = tf.constant([[2, 2]])

#创建矩阵乘法
product = tf.subtract(m1, m2)
#定义Session
with tf.Session() as sess:
    print(sess.run(product))

三、变量要初始化

当定义变量时:

m1 = tf.Variable([[3, 3]])
m2 = tf.Variable([[2, 2]])

在Tensorflow的Session中一定要初始化变量,正确写法如下代码所示:

m1 = tf.Variable([[3, 3]])
m2 = tf.constant([[2, 2]])

#创建矩阵乘法
product = tf.subtract(m1, m2)
#print(product)   Tensor("MatMul:0", shape=(1, 1), dtype=int32)
result = tf.add(m1, product)
#定义Session

Init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(Init)
    print(sess.run(product))
    print(sess.run(result))

四、写一个循环ok?

ok!

state = tf.Variable(0)
#定义一个add->op
add = tf.add(state, 1)
update = tf.assign(state, add)

Init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(Init)
    print(sess.run(state))
    for _ in range(5):
        sess.run(update)
        print(sess.run(state)) # 0 1 2 3 4 5

五 Feed和Fetch

Fetch个人的理解就是在会话中一次sess.run(),运行多个op操作:

input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)

add = tf.add(input3, input2)
mul = tf.multiply(input1, add)

with tf.Session() as sess:
    result = sess.run([mul, add])  #Fetch   运行多个op
    #print(result)

Feed个人的理解就是在op调用的时候,可以向op送入数据:

#创建占位符
input4 = tf.placeholder(tf.float32)
input5 = tf.placeholder(tf.float32)
output = tf.multiply(input4, input5)

with tf.Session() as sess:
    print(sess.run(output,feed_dict={input4: [4.], input5: [5.]})) #feed 对占位符变量临时赋(喂)值     输出20.
发布了15 篇原创文章 · 获赞 2 · 访问量 2196

猜你喜欢

转载自blog.csdn.net/Mr_WangYC/article/details/103190658
今日推荐