Tensotflow1.0入门(一)-tensorflow的设计理念和基本概念

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

Tensorflow的设计理念
1.将图的定义和图的运行完全分开
2.tensorflow中涉及的运算都要放在图中,而图的运行只发生在会话(session)中,开启会话后,就可以用数据去填充。关闭会话后,就不能进行计算了。

以上两个理念体现在,例子:

# coding=utf-8
'''
Created on 2019年4月1日

@author: admin
'''

import tensorflow as tf

# 创建图
a = tf.constant([2.0,3.0])
b = tf.constant([4.0,5.0])
c = a*b

# 查看一下运算结果,发现并没有进行计算
print(c)
# Tensor("mul:0", shape=(2,), dtype=float32)

# 创建会话
sess = tf.Session()
# 查看运算结果,发现已经有结果了
print(sess.run(a))
print(sess.run([a,b]))
print(sess.run(c))
sess.close()
# [2. 3.]
# [array([2., 3.], dtype=float32), array([4., 5.], dtype=float32)]
# [ 8. 15.]

tensorflow的基本概念
1.图
整个操作任务就是图
2.会话
启动图并按照图进行填充(feed),计算,并获取结果(fetch)
3.设备
tensorflow为了实现分布式执行操作,充分利用计算资源,可以明确指定操作在哪个设备上执行,通过tf.device("/gpu:1")来指定.
4.变量
(1)创建变量

w = tf.Variable(tf.random_normal([1,10]))

# 要初始化后才能计算
input_data = tf.Variable(1,dtype=np.float32)
input_data2 = tf.Variable(1,dtype=np.float32)
result = tf.add(input_data,input_data2)
init = tf.global_variables_initializer()
sess = tf.Session()
print(sess.run(init))
print(sess.run(result))
#2.0

(2)创建常量

a = tf.constant([[2,2]])

(3)创建填充,在构建图的时候使用tf.placeholder()临时代替任意操作的张量,在Session run的时候再加载

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)
sess = tf.Session()
sess.run([ouptput],feed_dict{input1:[5.],input2:[8:]})

5.内核
是能够运行在特定设备(CPU,GPU)上的一种对操作的实现,同一个操作可能会对应多个内核

参考:《TensorFlow 技术解析与实战》

猜你喜欢

转载自blog.csdn.net/u011311291/article/details/88959590