【TensorFlow】TensorFlow第一课:安装与基本概念

来源:互联网 发布:mac axure 没响应 编辑:程序博客网 时间:2024/04/29 16:09

,安装

    Google官方在11月29号的开发者博客中宣布新的版本(0.12)将 增加对Windows的支持,所以对于windows的用户来说,安装TensorFlow将会轻松很多,安装过程非常简单,不过也有一些需要手动调整。

    TensorFlow 有两个版本:CPU 版本和 GPU 版本。GPU 版本需要 CUDA 和 cuDNN 的支持,CPU 版本不需要。如果你要安装 GPU 版本,请先这里 确认你的显卡支持 CUDA

     CPU的版本安装很简单,我是在Anaconda下采样pip的方式安装的:

     在Anaconda Prompt模式下,使用命令:

pip install  tensorflow

     可以使用如下代码来测试,安装情况:

>>>import tensorflow as tf  >>>sess = tf.Session()  >>>a = tf.constant(10)  >>>b = tf.constant(22)  >>>print(sess.run(a + b))  32  
    

二,基本概念

    1,选择TensorFlow的原因:

    a,Google 很强大;         b,Python接口;           c,高移植性;     d,可视化强;     e,社区强大

    2,TensorFlow的核心概念:Graph和Session

    TensorFlow:张量在图中流动。

    类似于spark的惰性计算,TensorFlow是先定义图,然后再计算的。这种计算的定义和执行被分割开来的操作,有利于做分布式处理。

    Tensor+Flow:张量在图中通过运算(op)进行传递和变换。Tensor可以被理解成n维矩阵。

    模型跑起来, 你需要2步:一,描绘整幅图(定义计算);二,  session当中执行图中的运算 



    1,Session与Graph

    import tensorflow as tf    a = tf.add(3,5)    sess = tf.Session()    print sess.run(a)    sess.close()
    Session会在计算图里找到a的依赖, 把依赖的节点都进行计算 
    为了便捷建议写法如下:

   import tensorflow as tf   a = tf.add(3,5)   with tf.Session() as sess:       print sess.run(a)

     使用with语句,程序最后会自动关闭Session。

    假如要计算的表达式是:(x*y)的(x+y次幂)。

    图构建如下:


    代码如下:

    x= 2    y= 3    op1=tf.add(x, y)    op2=tf.mul(x, y)    op3=tf.pow(op2,op1)    with tf.Session() as sess:        op3= sess.run(op3)
    如果需要可以同时运行几个运算节点:

    with tf.Session() as sess:        z, not_useless= sess.run([pow_op, useless])


三,了解tesnorboard 

        tesnorboard 是TensorFlow可视化的利器,其原理就是TF在运行的过程中不断的将session写入到日志文件中,然    后tesnorboard 从日志文件中读取数据,最后做可视化。如下代码所示:


  import tensorflow as tfa = tf.constant(2)b = tf.constant(3)x = tf.add(a, b)with tf.Session() as sess:    #写到日志文件里    writer = tf.summary.FileWriter('./graphs, sess.graph)   print sess.run(x) writer.close() # 关闭writer    显示时在命令行端运行如下代码:$ python [yourprogram].py$ tensorboard --logdir="./graphs" --port 7001


    打开google浏览器访问: http://localhost:7001/     就能看到下图:



四,TensorFlow的常量、变量和操作


     TensorFlow和numpy其实很像。

1,常量

    常量的定义:

  常量的定义:tf.constant(value,dtype=None, shape=None,name='Const', verify_shape=False)
  代码如下所示:

a = tf.constant([2, 2], name="a")b = tf.constant([[0, 1], [2, 3]], name="b")x = tf.add(a, b, name="add")y = tf.mul(a, b, name="mul")with tf.Session() as sess:x, y = sess.run([x, y])print x, y# >> [5 8] [6 12]


2,变量

tf.constantop, 而tf.Variable是一个类, 初始化的对象有多个op

#createvariable a withscalar valuea=tf.Variable(2, name="scalar")#createvariable b as a vector值为2,3的向量b = tf.Variable([2, 3], name="vector")#createvariable c as a2x2 matrix 值为0,1,2,3的矩阵c = tf.Variable([[0, 1], [2, 3]], name="matrix")# create variable W as 784 x 10tensor,filledwith zerosW = tf.Variable(tf.zeros([784,10]))

变量的创建只是创建,在使用变量之前,一定要初始化!!

初始化的方法有三种:

a,最简单的初始化全部变量方法:

  

init= tf.global_variables_initializer()withtf.Session()as sess:sess.run(init)
b,初始化一个变量子集

init_ab=tf.variables_initializer([a,b], name="init_ab")withtf.Session()as sess:sess.run(init_ab)

c,初始化单个变量

W= tf.Variable(tf.zeros([784,10]))withtf.Session()as sess:sess.run(W.initializer)

输出变量内容: Eval()函数

3,操作

tensor上可以进行各种运算/变换

常用的操作

a=tf.constant([3, 6])b=tf.constant([2, 2])tf.add(a,b)#>>[5 8]tf.add_n([a,b,b])#>>[710]tf.mul(a,b)#>>[612]tf.matmul(a,b)#>> ValueErrortf.matmul(tf.reshape(a,[1,2]),tf.reshape(b,[2,1]))#>> [[18]]tf.div(a,b)#>>[1 3]tf.mod(a,b)#>>[1 0]

4,placeholder

通过placeholder可以存放用于训练的数据 :tf.placeholder(dtype, shape=None, name=None)

#createaplaceholderoftypefloat32-bit,shapeisavectorof3 elementsa=tf.placeholder(tf.float32, shape=[3])#createaconstantoftypefloat32-bit,shapeisavectorof3 elementsb=tf.constant([5,5,5], tf.float32)#usetheplaceholderasyouwouldaconstantora variablec=a + b #Shortfortf.add(a, b)withtf.Session()as sess:#feed[1,2,3]toplaceholderaviathedict{a:[1,2, 3]}printsess.run(c,{a:[1,2,3]})#thetensoraisthekey,notthestring ‘a’#>>[6,7, 8]
#createoperations,tensors,etc(usingthedefault graph)a=tf.add(2, 5)b=tf.mul(a, 3)withtf.Session()as sess:#defineadictionarythatsaystoreplacethevalueof'a'with 15replace_dict={a: 15}#Runthesession,passingin'replace_dict'asthevalueto 'feed_dict'sess.run(b,feed_dict=replace_dict)#returns 45


TEST