Tensorflow知識點總結(二)

大部分內容整理自《Tensorflow實戰Google深度學習框架》

Tensorflow的配置見前面的博文https://blog.csdn.net/jiugeshao/article/details/76370137

這裏Tensorflow的版本爲tensorflow-gpu1.2.0

計算圖

                                                            

Tensorflow是一個通過計算圖的形式來表述計算的編程系統,Tensorflow中每一個計算都是計算圖上的一個節點,而節點之間的連線描述了計算之間的依賴關係,節點表示數學操作,代表一個計算,計算的結果就保存在張量之中,邊線則表示節點相互聯繫的多位數據數組,即張量,Flow表達了張量之間通過計算相互轉化的過程。Tensorflow會將常量轉化成一種永遠輸出固定值的運算。張量的類型不匹配會報錯

Tensorflow程序一般分爲兩個階段:

  • 定義計算圖中所有的計算
  •  執行計算

如下是定義計算圖

import tensorflow as tf
g1 = tf.Graph()
with g1.as_default():
    a = tf.constant([11.0, 42.0], name="a")
    d = tf.constant([11.0, 42.0], name = "d")
    result1 = a - d
    v = tf.get_variable("v",initializer=tf.zeros_initializer()(shape=[1]))
    print("a,v: ",a,v)
    print("a.dtype: ",a.dtype)
    print("tf.graphkeys.variable: ", tf.GraphKeys.VARIABLES)

執行結果爲:

a,v:  Tensor("a:0", shape=(2,), dtype=float32) <tf.Variable 'v:0' shape=(1,) dtype=float32_ref>
a.dtype:  <dtype: 'float32'>
tf.graphkeys.variable:  variables
 

Tensorflow使用會話模式有兩種,第一種:

使用會話是可以像with tf.Session(graph=g1) as sess:指定具體會話

import tensorflow as tf
import numpy as np
import tensorboard
a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([2.0, 3.0], name="b")
print("a: ",a)
result = a + b
print("result: " ,result)

with tf.Session() as sess:
    print("sess.run(result): ",sess.run(result))
    print(tf.get_default_graph())

計算結果爲:

a:  Tensor("a:0", shape=(2,), dtype=float32)
result:  Tensor("add:0", shape=(2,), dtype=float32)

sess.run(result):  [3. 5.]
<tensorflow.python.framework.ops.Graph object at 0x000001D9946E4898>

第二種:

import tensorflow as tf
n1 = tf.constant(["1234", "6789"])
n2 = tf.string_to_number(n1, out_type=tf.float32)
sess = tf.Session()
result = sess.run(n2)
print(result)

結果爲:[1234. 6789.]

詳細的一些配置,擴展可以用時再查找。需要了解tf.add_to_collection使用, 共享變量的使用方法,配合Variable_scope一起使用的get_Variable方式,feed機制,生成張量的操作,變量初始化和tf.assign(有副作用),用tensorflow也能實現機器學習,如線性迴歸問題,

2. 可以手動實驗Tensorflow遊樂場及神經網絡簡介

3. tensorboard可視化

    這裏比較下keras和tensorflow加載mnist數據集的方式:

  (1)#使用keras自帶的mnist工具

from keras.datasets import mnist
import numpy
from keras import backend as K
X_train, y_train), (X_test, y_test) = mnist.load_data()

   該會去去找一鏈接來下載數據庫,但由於一般電腦都沒有設置翻牆功能,可以提前下載mnist.npz,然後放到

    C:\Users\76764\.keras\datasets目錄下,這邊的76764是用戶名,可以視自己的電腦而定,該文件我已經上傳至網盤

                                                     

    (2) 直接讀本地的mnist文件,如下格式文件:

                                                                    

 

import numpy as np
from keras.datasets import mnist
def load_mnist(path, kind='train'):
    """Load MNIST data from `path`"""
    labels_path = os.path.join(path,
                               '%s-labels.idx1-ubyte'
                               % kind)
    images_path = os.path.join(path,
                               '%s-images.idx3-ubyte'
                               % kind)

    print("labels_path: ",labels_path)
    print("images_path: ", images_path)
    with open(labels_path, 'rb') as lbpath:
        magic, n = struct.unpack('>II',
                                 lbpath.read(8))
        labels = np.fromfile(lbpath,
                             dtype=np.uint8)

    with open(images_path, 'rb') as imgpath:
        magic, num, rows, cols = struct.unpack('>IIII',
                                               imgpath.read(16))
        images = np.fromfile(imgpath,
                             dtype=np.uint8).reshape(len(labels), 784)

    return images, labels

path = ".\\mnist"
X_train, y_train = load_mnist(path, kind='train')

path = ".\\mnist"
X_test, y_test = load_mnist(path, kind='t10k')

print("X_train: ",X_train.T.shape, X_train.dtype)
print('y_train: ',y_train.T.shape, y_train.dtype)
print("X_test: ",X_test.shape, X_test.dtype)
print("y_test: ",y_test.shape, y_test.dtype)

  path爲保存有上面提到的文件的文件夾名

 (3)讀取如下的minist本地圖片

                                     

  

import os
import cv2
import numpy as np
import pydot
import graphviz

ef loadData(path, number):
    data = np.empty((number, 1, 28, 28), dtype="float32")  # empty與ones差不多原理,但是數值隨機,類型隨後面設定
    labels = np.empty((number,), dtype="uint8")
    listImg = os.listdir(path)
    count = 0
    for img in listImg:
        imgData = cv2.imread(path + '/' + img, 0)  # 數據
        l = int(img.split('.')[0])  # 答案
        arr = np.asarray(imgData, dtype="float32")  # 將img數據轉化爲數組形式
        data[count, :, :, :] = arr  # 將每個三維數組賦給data
        labels[count] = l  # 取該圖像的數值屬性作爲標籤
        count = count + 1
        path, " loaded ", count
        if count >= number:
            break
    return data, labels


# 從圖片文件加載數據
trainData, trainLabels = loadData('./mnistCnn-others_code/mnist', 22000)
testData, testLabels = loadData('./mnistCnn-others_code/mnist', 1)

  在使用tensorflow的過程中經常需要可視化計算圖,可以通過tensorboard來實現,可參考該博客,相關例程都有實現

發佈了24 篇原創文章 · 獲贊 24 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章