Tensorflow基本用法

一、概念

    Tensorflow是一个编程系统,使用图(graphs)来表示计算任务,图(graphs)中的节点称之为op (operation),一个op获得0个或多个Tensor,执行计算,产生0个或多个Tensor。Tensor 看作是 一个 n 维的数组或列表。图必须在会话(Session)里被启动。

二、Tensorflow结构


解释:

1、张量(tensor),即任意维度的数据,一维、二维、三维、四维等数据统称为张量。而张量的流动则是指保持计算节点不变,让数据进行流动。这样的设计是针对连接式的机器学习算法,比如逻辑斯底回归,神经网络等。连接式的机器学习算法可以把算法表达成一张图,张量从图中从前到后走一遍就完成了前向运算;而残差从后往前走一遍,就完成了后向传播。

2、Variable变量

3、operation在TF的实现中,机器学习算法被表达成图,图中的节点是算子(operation).

4、会话(Session)客户端使用会话来和TF系统交互,一般的模式是,建立会话,此时会生成一张空图;在会话中添加节点和边,形成一张图,然后执行。

二、基本用法

import tensorflow as tf

x = tf.Variable([1,2])#定义一个变量
a = tf.constant([3,3])#定义一个常量
#增加一个减法op
sub = tf.subtract(x,a)
#增加一个加法op
add = tf.add(x,a)
init = tf.global_variables_initializer()#初始化操作
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(sub))
    print(sess.run(add))

#创造一个变量初始化为0
state = tf.Variable(0,name='counter')
#创建一个op,作用是使state加1
new_value = tf.add(state,1)
#赋值op
update = tf.assign(state,new_value)
#变量初始化
init = tf.global_variables_initializer()
with tf.Session() as sess:

 

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


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


with tf.Session() as sess:
    result = sess.run([mul,add])

    print(result)


  #Feed
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)


with tf.Session() as sees:
    #feed 的数据以字典的形式传入
    print(sess.run(output,feed_dict={input1:[7.],input2:[2.]}))

猜你喜欢

转载自blog.csdn.net/qq_27262727/article/details/80222402
今日推荐