1. 程式人生 > >三十六、深入理解tensorflow的session和graph

三十六、深入理解tensorflow的session和graph


tensorflow作為一個基於圖結構的深度學習框架,內部通過session實現圖和計算核心的互動,那麼這個圖是什麼樣的結構,session的工作原理又是什麼樣的呢?我們通過幾段程式碼來深入理解一下

tensorflow中的基本數學運算用法

import tensorflow as tf

sess = tf.Session()

a = tf.placeholder("float")
b = tf.placeholder("float")
c = tf.constant(6.0)
d = tf.mul(a, b)
y = tf.mul(d, c)
print sess.run(y, feed_dict={a: 3, b: 3})

A
= [[1.1,2.3],[3.4,4.1]] Y = tf.matrix_inverse(A) print sess.run(Y) sess.close()

主要數字運算還包括:

tf.add
tf.sub
tf.mul
tf.div
tf.mod
tf.abs
tf.neg
tf.sign
tf.inv
tf.square
tf.round
tf.sqrt
tf.pow
tf.exp
tf.log
tf.maximum
tf.minimum
tf.cos
tf.sin

主要矩陣運算還包括:

tf.diag生成對角陣
tf.transpose
tf.matmul
tf.matrix_determinant計算行列式的值
tf.matrix_inverse計算矩陣的逆

插播小甜點:tensorboard使用

tensorflow因為程式碼執行過程是先構建圖,然後在執行,所以對中間過程的除錯不太方便,所以提供了一個tensorboard工具來便於除錯,用法如下:

在訓練時會提示寫入事件檔案到哪個目錄(比如:/tmp/tflearn_logs/11U8M4/)

執行如下命令並開啟http://192.168.1.101:6006就能看到tensorboard的介面

tensorboard --logdir=/tmp/tflearn_logs/11U8M4/

什麼是Graph和Session

為了步入正題,我們通過一段程式碼來展示Graph和Session的使用

import tensorflow as
tf with tf.Graph().as_default() as g: with g.name_scope("myscope") as scope: # 有了這個scope,下面的op的name都是類似myscope/Placeholder這樣的字首 sess = tf.Session(target='', graph = g, config=None) # target表示要連線的tf執行引擎 print "graph version:", g.version # 0 a = tf.placeholder("float") print a.op # 輸出整個operation資訊,跟下面g.get_operations返回結果一樣 print "graph version:", g.version # 1 b = tf.placeholder("float") print "graph version:", g.version # 2 c = tf.placeholder("float") print "graph version:", g.version # 3 y1 = tf.mul(a, b) # 也可以寫成a * b print "graph version:", g.version # 4 y2 = tf.mul(y1, c) # 也可以寫成y1 * c print "graph version:", g.version # 5 operations = g.get_operations() for (i, op) in enumerate(operations): print "============ operation", i+1, "===========" print op # 一個結構,包括:name、op、attr、input等,不同op不一樣 assert y1.graph is g assert sess.graph is g print "================ graph object address ================" print sess.graph print "================ graph define ================" print sess.graph_def print "================ sess str ================" print sess.sess_str print sess.run(y1, feed_dict={a: 3, b: 3}) # 9.0 feed_dictgraph中的元素和值的對映 print sess.run(fetches=[b,y1], feed_dict={a: 3, b: 3}, options=None, run_metadata=None) # 傳入的feches和返回值的shape相同 print sess.run({'ret_name':y1}, feed_dict={a: 3, b: 3}) # {'ret_name': 9.0} 傳入的feches和返回值的shape相同 assert tf.get_default_session() is not sess with sess.as_default(): # 把sess作為預設的session,那麼tf.get_default_session就是sess, 否則不是 assert tf.get_default_session() is sess h = sess.partial_run_setup([y1, y2], [a, b, c]) # 分階段執行,引數指明瞭feches和feed_dict列表 res = sess.partial_run(h, y1, feed_dict={a: 3, b: 4}) # 12 執行第一階段 res = sess.partial_run(h, y2, feed_dict={c: res}) # 144.0 執行第二階段,其中使用了第一階段的執行結果 print "partial_run res:", res sess.close()

輸出如下:

graph version: 0
name: "myscope/Placeholder"
op: "Placeholder"
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
    }
  }
}

graph version: 1
graph version: 2
graph version: 3
graph version: 4
graph version: 5
============ operation 1 ===========
name: "myscope/Placeholder"
op: "Placeholder"
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
    }
  }
}

============ operation 2 ===========
name: "myscope/Placeholder_1"
op: "Placeholder"
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
    }
  }
}

============ operation 3 ===========
name: "myscope/Placeholder_2"
op: "Placeholder"
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
    }
  }
}

============ operation 4 ===========
name: "myscope/Mul"
op: "Mul"
input: "myscope/Placeholder"
input: "myscope/Placeholder_1"
attr {
  key: "T"
  value {
    type: DT_FLOAT
  }
}

============ operation 5 ===========
name: "myscope/Mul_1"
op: "Mul"
input: "myscope/Mul"
input: "myscope/Placeholder_2"
attr {
  key: "T"
  value {
    type: DT_FLOAT
  }
}

================ graph object address ================
<tensorflow.python.framework.ops.Graph object at 0x1138702d0>
================ graph define ================
node {
  name: "myscope/Placeholder"
  op: "Placeholder"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "shape"
    value {
      shape {
      }
    }
  }
}
node {
  name: "myscope/Placeholder_1"
  op: "Placeholder"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "shape"
    value {
      shape {
      }
    }
  }
}
node {
  name: "myscope/Placeholder_2"
  op: "Placeholder"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "shape"
    value {
      shape {
      }
    }
  }
}
node {
  name: "myscope/Mul"
  op: "Mul"
  input: "myscope/Placeholder"
  input: "myscope/Placeholder_1"
  attr {
    key: "T"
    value {
      type: DT_FLOAT
    }
  }
}
node {
  name: "myscope/Mul_1"
  op: "Mul"
  input: "myscope/Mul"
  input: "myscope/Placeholder_2"
  attr {
    key: "T"
    value {
      type: DT_FLOAT
    }
  }
}
versions {
  producer: 15
}

================ sess str ================

9.0
[array(3.0, dtype=float32), 9.0]
{'ret_name': 9.0}
partial_run res: 144.0

tensorflow的Session是如何工作的

Session是Graph和執行者之間的媒介,Session.run()實際上將graph、fetches、feed_dict序列化到位元組陣列中,並呼叫tf_session.TF_Run(參見/usr/local/lib/python2.7/site-packages/tensorflow/python/client/session.py)

而這裡的tf_session.TF_Run實際上呼叫了動態連結庫_pywrap_tensorflow.so中實現的_pywrap_tensorflow.TF_Run介面(參見/usr/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py),這個動態連結庫是tensorflow提供的諸多語言介面中python語言的介面

事實上這裡的_pywrap_tensorflow.so和pywrap_tensorflow.py是通過SWIG工具自動生成,大家都知道tensorflow核心語言是c語言,這裡是通過SWIG生成了各種指令碼語言的介面

相關推薦

深入理解tensorflow的sessiongraph

tensorflow作為一個基於圖結構的深度學習框架,內部通過session實現圖和計算核心的互動,那麼這個圖是什麼樣的結構,session的工作原理又是什麼樣的呢?我們通過幾段程式碼來深入理解一下 tensorflow中的基本數學運算用法 import tensorflow as tf sess

python學習之Flask框架: 藍圖單元測試

一、藍圖和單元測試: 1.藍圖: 隨著flask程式越來越複雜,我們需要對程式進行模組化的處理,之前學習過python的模組化管理,於是針對一個簡單的flask程式進行模組化處理 名詞解釋: 高內聚,低耦合:   所謂高內聚是指一個軟體模組是由相關性很強的程式碼組成,

rsync通過服務同步Linux系統日誌screen工具

rsync通過服務同步 Linux系統日誌 screen工具 三十六、rsync通過服務同步、Linux系統日誌、screen工具一、rsync通過服務同步該方式可以理解為:在遠程主機上建立一個rsync的服務器,在服務器上配置好各種應用,然後本機將作為客戶端連接遠程的服務器。啟動服務前要先編輯配

python 中subprocess介紹

空格 環境變量 不能 startup false 字符 nes import all import subprocess1.執行系統命令subprocess.call(‘ipconfig‘) #shell=False時,拼接命令分開寫,放在列表中,等於True時,可寫一塊,

【Android Studio安裝部署系列】從Android Studio3.1.4升級到Android studio3.2【以及創建android p模擬器(未成功)】

tps min 比較 安裝 bsp mda 下載 initial uil 版權聲明:本文為HaiyuKing原創文章,轉載請註明出處! 概述 因為想要使用Android P模擬器,所以需要將Android Studio升級到3.2版本以上。 按照官網的說法:參考《ht

最好用的懶載入

window.Echo=(function(window,document,undefined){'use strict';var store=[],offset,throttle,poll;var _inView=function(el){var coords=el.getBoundingClient

最好用的懶加載

use div ech lis func pre png class parseint window.Echo=(function(window,document,undefined){‘use strict‘;var store=[],offset,throttle,p

為什麼ConcurrentHashMap的讀操作不需要加鎖

我們知道,ConcurrentHashmap(1.8)這個併發集合框架是執行緒安全的,當你看到原始碼的get操作時,會發現get操作全程是沒有加任何鎖的,這也是這篇博文討論的問題——為什麼它不需要加鎖呢? ConcurrentHashMap的簡介 我想有基礎的同學知道在

HDFS的寫資料流程及網路拓撲概念

                                            HDFS的寫資料流程及網路拓撲概念 1、HDFS的寫資料流程 1)客戶端向namenode請求上傳檔案,nam

jquery手風琴效果

1.基本結構樣式 2.新增手風琴展開事件:當滑鼠進入某個圖片,展開當前圖片,其同胞兄弟合起來,並設定相應的樣式 注意:需要使用stop()處理連續多次滑動的情況; $(this).mouseenter(function(){    //設定span屬性&

《我學區塊鏈》—— 以太坊批量轉賬(空投)節省費用

三十五、智慧合約收發 ETH 詳解        前段時間 fcoin 的空投把 eth 堵得不成樣,看見好幾個空投竟然是一個個地 transfer轉賬,但是實際上如果用合約實現批量轉賬,不管是成功率還是效率都會高很多,還省 gas。        整個過程的模

從零開始之驅動發開linux驅動(linux中common clock framework[1]_consoumer)

部分內容來自下面幾位博主的文章,如有侵權,聯絡我刪除。 時鐘管理模組是linux系統為統一管理各硬體的時鐘而實現管理框架,負責所有模組的時鐘調節和電源管理。時鐘管理模組主要負責處理各硬體模組的工作頻率調節及電源切換管理。一個硬體模組要正常工作,必須先配置好硬體的

章節3-TestNG方法類註解

一、Test Suite(測試套件) 我們通常認為一個testcase就是一個測試方法,但是會有很多的testcase,所以我們不可能把所有的testcase放到同一個測試類中,假如需要測試的頁面有10個,我們需要建立不同的類來測試這10個頁面的具體功能,測試具體功能的測試用例會放到具體的測試類中,把這些所有

javaSE ()Runtime類Timer類兩個執行緒之間的通訊個及以上執行緒通訊sleepwait的區別

1、Runtime類: runtime類其實是單例模式(見上文)的一個體現,它的構造方法被私有化,可以在程式碼中輸入命令字串控制計算機 程式碼例項: package cn.xinhua; import java.io.IOException; public class Threa

深入理解JVM學習筆記(二JVM 記憶體分配----優先分配到eden&空間分配擔保)

一、優先分配到eden 我們寫一個程式來驗證物件優先分配到eden,原始碼如下: package com.zjt.test.jvm008; public class Main { public static void main(String[] args) { b

聊聊高並發(二四)解析java.util.concurrent各個組件(深入理解AQS(四)

sar 成功 通知 ati help write ng- ads 同步 近期總體過了下AQS的結構。也在網上看了一些講AQS的文章,大部分的文章都是泛泛而談。又一次看了下AQS的代碼,把一些新的要點拿出來說一說。 AQS是一個管程。提供了一個主要的同步器的

Linux網絡相關firewalldnetfilternetfilter5表5鏈介紹

Linux網絡 filewalld和netfilter netfilter5表5鏈 iptables語法 三十一、Linux網絡相關、firewalld和netfilter、netfilter5表5鏈介紹、iptables語法一、Linux網絡相關(一)ifconfig:查看網卡IP,若沒有該

Linux 進程與信號---system 函數 進程狀態切換

idt erro lib IV lin sig 進入 空指針 權限 26.1 system 函數 26.1.1 函數說明 system(執行shell 命令)相關函數 fork,execve,waitpid,popen 1 #include <stdlib.h>

python學之Flask框架()資料庫:mysql資料庫及Flask-SQLAlchemy

一、資料庫知識回顧: 1.SQL:關係型資料庫,支援結構化查詢語言: 關係型資料庫:以表的形式儲存; 支援結構化查詢語言:SQL語句; 列數固定;行數可變,定義資料,主鍵、外來鍵,引用同表或不同表的主鍵,這種聯絡稱為關係. 2.關於正規化: 第一

PostConstructPreDestroy

簡介 Java EE5 引入了@PostConstruct和@PreDestroy這兩個作用於Servlet生命週期的註解,實現Bean初始化之前和銷燬之前的自定義操作。此文主要說明@PostConstruct。 API使用說明 以下為@PostConstruct的API使用說明: Post