TensorFlow 安装及入门

安装

TensorFlow官网按照教程安装。

这里写图片描述

这里写图片描述

入门

以下学习内容follow这篇博客

TensorFlow简介

TensorFlow是Google Brain Team开发的一个深度学习框架,使用的是data flow graph的模型进行计算。TF使用Python的API,可以布置在多个CPU,GPU上,并且有移动端的版本。可以在树莓派,Android,Windows,iOS,Linux上运行。

TF的计算模型是data flow graph,如下图:
这里写图片描述

整个模型在运行的时候就会从输入到输出。另外TF有个特点就是计算和具体执行时分开的,就是先定义一堆计算,整个框架描绘好,然后再开启一个session来执行。

tensor:n维数组,0维的就是scalar,一个数字;1维的就是vector;2维的就是matrix。

Session有两种写法
第一种:

import tensorflow as tf

a = tf.add(3,35)
sess = tf.Session()
sess.run(a)
sess.close()

第二种:

import tensorflow as tf

a = tf.add(3,35)
with tf.Session() as sess:
    sess.run(a)

为了节省计算量,session只计算与结果相关的部分,因此,需要计算什么就把上面加到run的list里。

x = 2
y = 3
add_op = tf.add(x,y)
mul_op = tf.multiply(x,y)
useless = tf.multiply(x,add_op)
pow_op = tf.pow(add_op,mul_op)


with tf.Session() as sess:
    print sess.run([pow_op, useless])

基本操作

常量申明

a = tf.constant([2, 3], name = "a")
b = tf.constant([[3, 1], [2, 9], [1, 3]], name = "b")
x = tf.add(a, b, name = "add")
y = tf.multiply(a, b, name = "mul")

with tf.Session() as sess:
    print sess.run([x, y])
    print x
    print y

注意:这里的add和mul是对应元素相加相乘,不同于一般的矩阵运算!
结果如下:

[array([[ 5,  4],
       [ 4, 12],
       [ 3,  6]], dtype=int32), array([[ 6,  3],
       [ 4, 27],
       [ 2,  9]], dtype=int32)]

基本初始化

# tensor初始化为0
# tf.zeros(shape, dtype = tf.float32, name = None)
print tf.zeros([2, 3], tf.int32) # [[0, 0, 0], [0, 0, 0]]


# tf.zeros_like(input_tensor, dtype = None, name = None, optimize = True)
input_tensor = [[1,2], [3,4], [5,6]]
print tf.zeros_like(input_tensor) # [[0,0], [0,0], [0,0]

# tensor初始化为1
# tf.ones(shape, dtype = tf.float32, name = None)
print tf.ones([3,2], tf.int32) # [[0, 0], [[0, 0], [0, 0]]

# tf.ones_like(input_tensor, dtype = None, name = None, optimize = True)
print tf.ones_like(input_tensor)  # [[1,1], [1,1], [1,1]

# tensor初始化为某个值
# tf.fill(dims, value, name = None)
print tf.fill([2,3],6) # [[6,6,6], [6,6,6]]

运行结果如下:

Tensor("zeros:0", shape=(2, 3), dtype=int32)
Tensor("zeros_like:0", shape=(3, 2), dtype=int32)
Tensor("ones:0", shape=(3, 2), dtype=int32)
Tensor("ones_like:0", shape=(3, 2), dtype=int32)
Tensor("Fill:0", shape=(2, 3), dtype=int32)

loading lazy

只有在需要的时候才会创建或者是初始化一个object。导致一个循环出现的时候,这个graph就重复了n遍

正常

a = tf.Variable(10, name = "a")
b = tf.Variable(20, name = "b")
z = tf.add(a, b, name = "add")

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    writer = tf.summary.FileWriter("./graphs", sess.graph)
    for _ in range(10):
        print sess.run(z)
    writer.close()

正常的图形
这里写图片描述

正常的结构
这里写图片描述

loading lazy

a = tf.Variable(10, name = "a")
b = tf.Variable(20, name = "b")

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    writer = tf.summary.FileWriter("./graphs", sess.graph)
    for _ in range(10):
        print sess.run(tf.add(a, b))
    writer.close()

loading lazy图形
这里写图片描述

loading lazy结构
这里写图片描述

猜你喜欢

转载自blog.csdn.net/liveway6/article/details/78919782
今日推荐