【TensorFlow】基本用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bqw18744018044/article/details/83187033

一、TensorFlow简介

1.TensorFlow是编程系统,使用图来表示计算任务。图中的结点被称为op,表示一个操作。一个op接收0个或多个Tensor进行计算,计算后输出0个或多个Tensor。

2.一个TensorFlow图描述了一个计算的过程,但是真正执行计算需要将图中Session中启动。Session会将图中的op分发到诸如CPU或GPU之类的设备上。

二、构造计算图

1.构建图的第一步是创建“源op”,源op不需要任何输入,例如常量。源op的输出被传递给其他的op做运算。

2.TensorFlow的Python库有一个默认的图,只需要向这个图中加入op。通常的应用,有这个默认的图就足够了。

import tensorflow as tf
# 下面的这些op都会加入到默认图中
# 创建常量op,产生一个1*2的矩阵
matrix1 = tf.constant([[3.,3.]])
# 创建另一个常量op,产生一个2*1的矩阵
matrix2 = tf.constant([[2.],[2.]])
# 创建一个矩阵乘法matmul op
product = tf.matmul(matrix1,matrix2)

三、启动图

构造完图后,就需要启动这个图。其他图通过Session对象来实现

# 启动默认图
sess = tf.Session()
# 执行与product相关的计算图,并将product的结果取回
result = sess.run(product)
print(result)
# 关闭会话
sess.close()
[[12.]]

使用python的with语法后,可以不需要显式的关闭session

with tf.Session() as sess:
    sess.run(product)
    print(result)
[[12.]]

四、交互式使用

在notebook这样的交互环境中可以使用InteractiveSession替代Session。使用Tensor.eval()和Operation.run()的方法代替Session.run()

import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.Variable([1.0,2.0])
a = tf.constant([3.0,3.0])
# 初始化变量x
x.initializer.run()
# 从x中减去a
sub = tf.subtract(x,a)
print(sub.eval())
[-2. -1.]

五、Tensor

Tensorflow使用tensor作为数据结构,op间传递的数据也是tensor.

# 使用TensorFLow实现一个简单的计数器

# 创建一个变量state,将其初始化为标量0,name为counter
state = tf.Variable(0,name='counter')
# 创建一个常量
one = tf.constant(1)
# 将one加到state中
new_value = tf.add(state,one)
# 将new_value复制给state(相当于state=new_value),用update代表这一操作
update = tf.assign(state,new_value)
# 在启动图后,必须初始化所有的变量
init_op = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(state))
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))
0
1
2
3

六、Fecth

为了取回操作中tensor内容,可以使用Session.run()方法,它会将对应的op结果保存下来。下标的例子中就是取回两个tensor

input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2,input3)
mul = tf.multiply(input1,intermed)
with tf.Session() as sess:
    # 取回mul和intermed
    result = sess.run([mul,intermed])
    print(result)
[21.0, 7.0]

七、Feed

feed是一种用于临时替代计算图中任意op的tensor的机制。你可以使用tf.placeholder()先创造一个占位符,此时这个op没有值。然后在run()再传递对应placeholder的值

input1 = tf.placeholder(tf.float32)
intpu2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)
with tf.Session() as sess:
    print(sess.run([output],feed_dict={input1:7.,input2:2.}))
[14.0]

猜你喜欢

转载自blog.csdn.net/bqw18744018044/article/details/83187033