斯坦福大学TensorFlow课程笔记(cs20si):#1

Tensor定义

tensor张量可以理解为n维数组:

  • 0维张量是一个数(Scalar/number),
  • 1维张量是向量(Vector),
  • 2维张量是矩阵(Martrix),
  • 以此类推...

基础运算

import tensorflow as tf
a=tf.add(3,5)
print(a)
Tensor("Add:0", shape=(), dtype=int32)

TF的加法方法,但是通常的赋值并不是正常运行加法。
需要将被赋值的变量a放入session运行才能看到运算结果。

a=tf.add(3,5)
sess=tf.Session()
print(sess.run(a))
sess.close()
8

将运算结果存入sess稍后再用的写法

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

tf.Session()封装了一个执行运算的环境,用tensor对象内的赋值进行运算

混合运算

x=2
y=3
op1 =tf.add(x,y)
op2=tf.multiply(x,y)
op3=tf.pow(op2,op1)
with tf.Session() as sess:
    op3=sess.run(op3)
    print(op3)
7776

Subgraphs

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:
    z=sess.run(pow_op)
    print(z)
15625

由于求Z值并不需要计算useless部分,所以session并没有计算它

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:
    z,not_useless=sess.run([pow_op,useless])
    print(z)
    print(not_useless)
15625
10

同时进行两个计算

Graph

g=tf.Graph()
with g.as_default():
    x=tf.add(3,5)
    
sess=tf.Session(graph=g)
with tf.Session() as sess: #此处两行的打包方式已经过时,如果报错需要改成下面的格式
    sess.run(g)

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in __init__(self, fetches, contraction_fn)
    270         self._unique_fetches.append(ops.get_default_graph().as_graph_element(
--> 271             fetch, allow_tensor=True, allow_operation=True))
    272       except TypeError as e:


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
   3034     with self._lock:
-> 3035       return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
   3036 


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
   3123       raise TypeError("Can not convert a %s into a %s." % (type(obj).__name__,
-> 3124                                                            types_str))
   3125 


TypeError: Can not convert a Graph into a Tensor or Operation.


During handling of the above exception, another exception occurred:


TypeError                                 Traceback (most recent call last)

<ipython-input-20-5c5906e5d961> in <module>()
      5 sess=tf.Session(graph=g)
      6 with tf.Session() as sess:
----> 7     sess.run(g)


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    887     try:
    888       result = self._run(None, fetches, feed_dict, options_ptr,
--> 889                          run_metadata_ptr)
    890       if run_metadata:
    891         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1103     # Create a fetch handler to take care of the structure of fetches.
   1104     fetch_handler = _FetchHandler(
-> 1105         self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
   1106 
   1107     # Run request and get response.


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in __init__(self, graph, fetches, feeds, feed_handles)
    412     """
    413     with graph.as_default():
--> 414       self._fetch_mapper = _FetchMapper.for_fetch(fetches)
    415     self._fetches = []
    416     self._targets = []


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in for_fetch(fetch)
    240         if isinstance(fetch, tensor_type):
    241           fetches, contraction_fn = fetch_fn(fetch)
--> 242           return _ElementFetchMapper(fetches, contraction_fn)
    243     # Did not find anything.
    244     raise TypeError('Fetch argument %r has invalid type %r' %


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in __init__(self, fetches, contraction_fn)
    273         raise TypeError('Fetch argument %r has invalid type %r, '
    274                         'must be a string or Tensor. (%s)'
--> 275                         % (fetch, type(fetch), str(e)))
    276       except ValueError as e:
    277         raise ValueError('Fetch argument %r cannot be interpreted as a '


TypeError: Fetch argument <tensorflow.python.framework.ops.Graph object at 0x0000018E70371A20> has invalid type <class 'tensorflow.python.framework.ops.Graph'>, must be a string or Tensor. (Can not convert a Graph into a Tensor or Operation.)

教程的例子有报错,需要改成下面的格式

g=tf.Graph()
with g.as_default():
    x=tf.add(3,5)
    

with tf.Session(graph=g) as sess: #将上面的两行改成一行
    sess.run(x)                   #不能直接运行graph

g=tf.Graph()
with g.as_default():
a=3
b=5
x=tf.add(a,b)
sess = tf.Session(graph=g)
sess.close()

向graph内添加加法运算,并且设为默认graph

g1=tf.get_default_graph()
g2=tf.graph()
#将运算加入到默认graph
with g1.as_default():
    a=tf.Constant(3)       #不会报错,但推荐添加到自己创建的graph里
    
#将运算加入到用户创建的graph
with g2.as_default():
    b=tf.Constant(5)

建议不要修改默认graph

** Graph 的优点 **

  • 节省运算资源,只计算需要的部分
  • 将计算分解为更小的部分
  • 让分布式运算更方便,向多个CPU,GPU或其它设备分配任务
  • 适合那些使用directed graph的机器学习算法

Graph 与 Session 的区别

  • Graph定义运算,但不计算任何东西,不保存任何数值,只存储你在各个节点定义的运算。
  • Session可运行Graph或一部分Graph,它负责在一台或多台机器上分配资源,保存实际数值,中间结果和变量。

下面通过以下例子具体阐明二者的区别:

graph=tf.Graph()
with graph.as_default():#每次TF都会生产默认graph,所以前两行其实并不需要
    variable=tf.Variable(42,name='foo')
    initialize=tf.global_variables_initializer()
    assign=variable.assign(13)

创建变量,初始化值42,之后赋值13

graph=tf.Graph()
with graph.as_default():#每次TF都会生产默认graph,所以前两行其实并不需要
    variable=tf.Variable(42,name='foo')
    initialize=tf.global_variables_initializer()
    assign=variable.assign(13)

with tf.Session(graph=graph) as sess:  
    sess.run(initialize)      #记得将计算步骤在此处列出来
    sess.run(assign)
    print(sess.run(variable))
13

定义的计算数量达到三个时就要使用graph。但是variable每次运算都要在session内run一遍,如果跳过此步骤,就无法获取运算后变量数值。(也就相当于没计算过)

graph=tf.Graph()
with graph.as_default():#每次TF都会生产默认graph,所以前两行其实并不需要
    variable=tf.Variable(42,name='foo')
    initialize=tf.global_variables_initializer()
    assign=variable.assign(13)

with tf.Session(graph=graph) as sess:
    print(sess.run(variable))    #未列出计算步骤所以报错
---------------------------------------------------------------------------

FailedPreconditionError                   Traceback (most recent call last)

~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1322     try:
-> 1323       return fn(*args)
   1324     except errors.OpError as e:


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1301                                    feed_dict, fetch_list, target_list,
-> 1302                                    status, run_metadata)
   1303 


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\errors_impl.py in __exit__(self, type_arg, value_arg, traceback_arg)
    472             compat.as_text(c_api.TF_Message(self.status.status)),
--> 473             c_api.TF_GetCode(self.status.status))
    474     # Delete the underlying status object from memory otherwise it stays alive


FailedPreconditionError: Attempting to use uninitialized value foo
     [[Node: _retval_foo_0_0 = _Retval[T=DT_INT32, index=0, _device="/job:localhost/replica:0/task:0/device:CPU:0"](foo)]]


During handling of the above exception, another exception occurred:


FailedPreconditionError                   Traceback (most recent call last)

<ipython-input-25-cb7c04ce65af> in <module>()
      6 
      7 with tf.Session(graph=graph) as sess:
----> 8     print(sess.run(variable))


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    887     try:
    888       result = self._run(None, fetches, feed_dict, options_ptr,
--> 889                          run_metadata_ptr)
    890       if run_metadata:
    891         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1118     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1119       results = self._do_run(handle, final_targets, final_fetches,
-> 1120                              feed_dict_tensor, options, run_metadata)
   1121     else:
   1122       results = []


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1315     if handle is None:
   1316       return self._do_call(_run_fn, self._session, feeds, fetches, targets,
-> 1317                            options, run_metadata)
   1318     else:
   1319       return self._do_call(_prun_fn, self._session, handle, feeds, fetches)


~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1334         except KeyError:
   1335           pass
-> 1336       raise type(e)(node_def, op, message)
   1337 
   1338   def _extend_graph(self):


FailedPreconditionError: Attempting to use uninitialized value foo
     [[Node: _retval_foo_0_0 = _Retval[T=DT_INT32, index=0, _device="/job:localhost/replica:0/task:0/device:CPU:0"](foo)]]
graph=tf.Graph()
with graph.as_default():#每次TF都会生产默认graph,所以前两行其实并不需要
    variable=tf.Variable(42,name='foo')
    initialize=tf.global_variables_initializer()
    assign=variable.assign(13)

with tf.Session(graph=graph) as sess:  
    sess.run(initialize)      #计算步骤,列到第几步就计算到第几步
    print(sess.run(variable))
42
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容