0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內(nèi)不再提示

【連載】深度學習筆記7:Tensorflow入門

人工智能實訓營 ? 2018-08-24 18:31 ? 次閱讀

從前面的學習筆記中,筆者和大家一起使用了 numpy 一步一步從感知機開始到兩層網(wǎng)絡以及最后實現(xiàn)了深度神經(jīng)網(wǎng)絡算法搭建。而后我們又討論了改善深度神經(jīng)網(wǎng)絡的基本方法,包括神經(jīng)網(wǎng)絡的正則化、參數(shù)優(yōu)化和調(diào)參等問題。這一切工作我們都是基于numpy 完成的,沒有調(diào)用任何深度學習框架。在學習深度學習的時候,一開始不讓大家直接上手框架可謂良苦用心,旨在讓大家能夠跟筆者一樣,一步一步通過 numpy 搭建神經(jīng)網(wǎng)絡的過程就是要讓你能夠更加深入的理解神經(jīng)網(wǎng)絡的架構(gòu)、基本原理和工作機制,而不是黑箱以視之。

但學習到這個階段,你已充分理解了神經(jīng)網(wǎng)絡的工作機制,馬上就要接觸更深層次的卷積神經(jīng)網(wǎng)絡(CNN)和遞歸神經(jīng)網(wǎng)絡(RNN),依靠純手工去搭建這些復雜的神經(jīng)網(wǎng)絡恐怕并不現(xiàn)實。這時候就該深度學習框架出場了。針對深度學習,目前有很多優(yōu)秀的學習框架,比如說筆者馬上要講的 Tensorflow,微軟的 CNTK,伯克利視覺中心開發(fā)的 caffe,以及別具一格的 PyTorch 和友好易用的 keras,本系列深度學習筆記打算從 Tensorflow 開始,對三大主流易用的深度學習框架 TensorflowPyTorchkeras 進行學習和講解。選擇這三個框架的原因在于其簡單易用、方便編程和運行速度相對較快。

作為谷歌的深度學習框架, Tensorflow 在深度學習領域可謂風頭無二。其中 Tensor 可以理解為類似于 numpy 的 N 維數(shù)組,名為張量; flow 則意味著 N 維數(shù)組的流計算,而 Tensor 的數(shù)據(jù)流計算形式則為一個計算圖的形式進行計算。這里重點提一下,如果大學本科期間的線性代數(shù)忘記了的話,我勸你趕緊回去翻一翻,線性代數(shù)和矩陣論是深度學習的基礎,希望你能熟練掌握。


先看個簡單的例子。

importtensorflowastf#Definey_hatconstant.Setto36.y_hat=tf.constant(36,name='y_hat')
#Definey.Setto39y=tf.constant(39,name='y')#Createavariableforthelossloss=tf.Variable((y-y_hat)**2,name='loss')#Wheninitisrunlater(session.run(init)),thelossvariablewillbeinitializedandreadytobecomputedinit=tf.global_variables_initializer()#Createasessionandprinttheoutputwithtf.Session()assession:
#Initializesthevariables
session.run(init)
#Printstheloss
print(session.run(loss))
9

在上述代碼中,我們首先定義了兩個常量,然后定義了一個 loss Tensor(變量),之后對變量進行初始化,創(chuàng)建計算會話,最后執(zhí)行會話計算并打印結(jié)果。所以我們可以看到運行 Tensorflow 的基本機制:
創(chuàng)建一些尚未被執(zhí)行的張量——
定義這些張量之間的運算操作——初始化這些張量——創(chuàng)建會話——執(zhí)行會話

需要注意的一點是,創(chuàng)建會話后一定要執(zhí)行這個會話,且看下面示例:

a=tf.constant(2)
b=tf.constant(10)
c=tf.multiply(a,b)
print(c)
Tensor("Mul:0",shape=(),dtype=int32)

在上面的示例中,我們創(chuàng)建了兩個 TensorTensor 之間的乘積運算,但直接打印的結(jié)果卻不是我們想要看到的 20. 原因則在于這里我們沒有創(chuàng)建會話并執(zhí)行,只是打印了兩個張量運算之后的張量。創(chuàng)建會話并執(zhí)行操作如下:

sess=tf.Session()
print(sess.run(c))
20

除了直接定義變量之外,我們還可以通過創(chuàng)建占位符變量來稍后為之賦值,然后在運行會話中傳入一個 feed_dict ,示例如下:

x=tf.placeholder(tf.int64,name='x')
print(sess.run(2*x,feed_dict={x:3}))
sess.close()
6

相信你已經(jīng)大致明白了基于張量運算的 Tensorflow 的底層運行機制了。總結(jié)而言就是:創(chuàng)建張量、初始化張量、創(chuàng)建會話并執(zhí)行。

下面展示幾個 Tensorflow 的神經(jīng)網(wǎng)絡計算的基礎函數(shù)示例。

線性函數(shù)
def linear_function():  
""" Implements a linear function: Initializes W to be a random tensor of shape (4,3) Initializes X to be a random tensor of shape (3,1) Initializes b to be a random tensor of shape (4,1) Returns: result -- runs the session for Y = WX + b """ np.random.seed(1) X = tf.constant(np.random.randn(3,1), name='X') W = tf.constant(np.random.randn(4,3), name='W') b = tf.constant(np.random.randn(4,1), name='b') Y = tf.add(tf.matmul(W, X), b) # Create the session using tf.Session() and run it with sess.run(...) on the variable you want to calculate init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) result = sess.run(Y) # close the session sess.close()
return result
計算sigmoid函數(shù)
def sigmoid(z):  
""" Computes the sigmoid of z Arguments: z -- input value, scalar or vector Returns: results -- the sigmoid of z """ x = tf.placeholder(tf.float32, name='x') sigmoid = tf.sigmoid(x)
with tf.Session() as sess: result = sess.run(sigmoid, feed_dict={x: z})
return result
計算損失函數(shù)

640?wx_fmt=png

def cost(logits, labels):  
""" Computes the cost using the sigmoid cross entropy Arguments: logits -- vector containing z, output of the last linear unit (before the final sigmoid activation) labels -- vector of labels y (1 or 0) Note: What we've been calling "z" and "y" in this class are respectively called "logits" and "labels" in the TensorFlow documentation. So logits will feed into z, and labels into y. Returns: cost -- runs the session of the cost (formula (2)) """ # Create the placeholders for "logits" (z) and "labels" (y) (approx. 2 lines) z = tf.placeholder(tf.float32, name='z') y = tf.placeholder(tf.float32, name='y') # Use the loss function (approx. 1 line) cost = tf.nn.sigmoid_cross_entropy_with_logits(logits=z, labels=y) # Create a session (approx. 1 line). See method 1 above. sess = tf.Session() # Run the session (approx. 1 line). sess.run(cost, feed_dict={z: logits, y: labels}) # Close the session (approx. 1 line). See method 1 above. sess.close()
return cost
one hot 編碼

640?wx_fmt=png

def one_hot_matrix(labels, C):  
""" Creates a matrix where the i-th row corresponds to the ith class number and the jth column corresponds to the jth training example. So if example j had a label i. Then entry (i,j) will be 1. Arguments: labels -- vector containing the labels C -- number of classes, the depth of the one hot dimension Returns: one_hot -- one hot matrix """ # Create a tf.constant equal to C (depth), name it 'C'. (approx. 1 line) C = tf.constant(C) # Use tf.one_hot, be careful with the axis (approx. 1 line) one_hot_matrix = tf.one_hot(labels, C, axis=0) # Create the session (approx. 1 line) sess = tf.Session() one_hot = sess.run(one_hot_matrix) # Close the session (approx. 1 line). See method 1 above. sess.close()
return one_hot
參數(shù)初始化
def ones(shape):  """
  Creates an array of ones of dimension shape
  Arguments:
  shape -- shape of the array you want to create

  Returns: 
  ones -- array containing only ones
  """
  # Create "ones" tensor using tf.ones(...). (approx. 1 line)
  ones = tf.ones(shape)  # Create the session (approx. 1 line)
  sess = tf.Session()  # Run the session to compute 'ones' (approx. 1 line)
  ones = sess.run(ones)  # Close the session (approx. 1 line). See method 1 above.
  sess.close()  
return ones

一頓操作之后,我們已經(jīng)將神經(jīng)網(wǎng)絡的一些基礎運算利用 Tensorflow 定義好了。在下一期筆記中,我們將學習如何使用 Tensorflow 搭建神經(jīng)網(wǎng)絡。

本文由《自興動腦人工智能》項目部 凱文 投稿。


聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學習之用,如有內(nèi)容侵權或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 人工智能
    +關注

    關注

    1787

    文章

    46124

    瀏覽量

    235420
  • 機器學習
    +關注

    關注

    66

    文章

    8308

    瀏覽量

    131904
  • 深度學習
    +關注

    關注

    73

    文章

    5424

    瀏覽量

    120630
收藏 人收藏

    評論

    相關推薦

    快速部署Tensorflow和TFLITE模型在Jacinto7 Soc

    電子發(fā)燒友網(wǎng)站提供《快速部署Tensorflow和TFLITE模型在Jacinto7 Soc.pdf》資料免費下載
    發(fā)表于 09-27 11:41 ?0次下載
    快速部署<b class='flag-5'>Tensorflow</b>和TFLITE模型在Jacinto<b class='flag-5'>7</b> Soc

    如何在Tensorflow中實現(xiàn)反卷積

    TensorFlow中實現(xiàn)反卷積(也稱為轉(zhuǎn)置卷積或分數(shù)步長卷積)是一個涉及多個概念和步驟的過程。反卷積在深度學習領域,特別是在圖像分割、圖像超分辨率、以及生成模型(如生成對抗網(wǎng)絡GANs)等任務中
    的頭像 發(fā)表于 07-14 10:46 ?444次閱讀

    TensorFlow是什么?TensorFlow怎么用?

    TensorFlow是由Google開發(fā)的一個開源深度學習框架,它允許開發(fā)者方便地構(gòu)建、訓練和部署各種復雜的機器學習模型。TensorFlow
    的頭像 發(fā)表于 07-12 16:38 ?407次閱讀

    tensorflow和pytorch哪個更簡單?

    TensorFlow和PyTorch都是用于深度學習和機器學習的開源框架。TensorFlow由Google Brain團隊開發(fā),而Py
    的頭像 發(fā)表于 07-05 09:45 ?426次閱讀

    tensorflow和pytorch哪個好

    :2015年由Google Brain團隊發(fā)布。 語言支持 :主要使用Python,也支持C++、Java等。 設計哲學 :TensorFlow是一個端到端的機器學習平臺,支持從研究到生產(chǎn)的所有階段
    的頭像 發(fā)表于 07-05 09:42 ?468次閱讀

    tensorflow簡單的模型訓練

    在本文中,我們將詳細介紹如何使用TensorFlow進行簡單的模型訓練。TensorFlow是一個開源的機器學習庫,廣泛用于各種機器學習任務,包括圖像識別、自然語言處理等。我們將從安裝
    的頭像 發(fā)表于 07-05 09:38 ?318次閱讀

    keras模型轉(zhuǎn)tensorflow session

    和訓練深度學習模型。Keras是基于TensorFlow、Theano或CNTK等底層計算框架構(gòu)建的。TensorFlow是一個開源的機器學習
    的頭像 發(fā)表于 07-05 09:36 ?329次閱讀

    如何使用Tensorflow保存或加載模型

    TensorFlow是一個廣泛使用的開源機器學習庫,它提供了豐富的API來構(gòu)建和訓練各種深度學習模型。在模型訓練完成后,保存模型以便將來使用或部署是一項常見的需求。同樣,加載已保存的模
    的頭像 發(fā)表于 07-04 13:07 ?672次閱讀

    TensorFlow的定義和使用方法

    TensorFlow是一個由谷歌人工智能團隊谷歌大腦(Google Brain)開發(fā)和維護的開源機器學習庫。它基于數(shù)據(jù)流編程(dataflow programming)的概念,將復雜的數(shù)學運算表示為
    的頭像 發(fā)表于 07-02 14:14 ?547次閱讀

    TensorFlow與PyTorch深度學習框架的比較與選擇

    深度學習作為人工智能領域的一個重要分支,在過去十年中取得了顯著的進展。在構(gòu)建和訓練深度學習模型的過程中,深度
    的頭像 發(fā)表于 07-02 14:04 ?646次閱讀

    FPGA在深度學習應用中或?qū)⑷〈鶪PU

    、筆記本電腦或機架式服務器上訓練神經(jīng)網(wǎng)絡時,這不是什么大問題。但是,許多部署深度學習模型的環(huán)境對 GPU 并不友好,比如自動駕駛汽車、工廠、機器人和許多智慧城市環(huán)境,在這些環(huán)境中硬件必須忍受熱、灰塵、濕度
    發(fā)表于 03-21 15:19

    如何使用TensorFlow構(gòu)建機器學習模型

    在這篇文章中,我將逐步講解如何使用 TensorFlow 創(chuàng)建一個簡單的機器學習模型。
    的頭像 發(fā)表于 01-08 09:25 ?817次閱讀
    如何使用<b class='flag-5'>TensorFlow</b>構(gòu)建機器<b class='flag-5'>學習</b>模型

    PyTorch與TensorFlow的優(yōu)點和缺點

    轉(zhuǎn)載自:冷凍工廠 ? 深度學習框架是簡化人工神經(jīng)網(wǎng)絡 (ANN) 開發(fā)的重要工具,并且其發(fā)展非常迅速。其中,TensorFlow 和 PyTorch 脫穎而出,各自在不同的機器學習領域
    的頭像 發(fā)表于 10-30 09:56 ?842次閱讀
    PyTorch與<b class='flag-5'>TensorFlow</b>的優(yōu)點和缺點

    深度學習的由來 深度學習的經(jīng)典算法有哪些

    深度學習作為機器學習的一個分支,其學習方法可以分為監(jiān)督學習和無監(jiān)督學習。兩種方法都具有其獨特的
    發(fā)表于 10-09 10:23 ?488次閱讀
    <b class='flag-5'>深度</b><b class='flag-5'>學習</b>的由來 <b class='flag-5'>深度</b><b class='flag-5'>學習</b>的經(jīng)典算法有哪些

    iTOP-RK3588開發(fā)板使用 tensorflow框架

    TensorFlow 是一個軟件庫或框架,由 Google 團隊設計,以最簡單的方式實現(xiàn)機器學習深度學習概念。它結(jié)合了優(yōu)化技術的計算代數(shù),便于計算許多數(shù)學表達式。
    發(fā)表于 10-08 10:04