TensorFlow 初級教程(三)

TensorFlow基本操做

import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 使用TensorFlow輸出Hello

# 建立一個常量操做( Constant op )
# 這個 op 會被做爲一個節點( node )添加到默認計算圖上.
#
# 該構造函數返回的值就是常量節點(Constant op)的輸出.
hello = tf.constant('Hello, TensorFlow!')

# 啓動TensorFlow會話
sess = tf.Session()


# 運行 hello 節點
print(sess.run(hello))
'''
TensorFlow library 的基本操做.
'''
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 基本常量操做
# T構造函數返回的值就是常量節點(Constant op)的輸出.
a = tf.constant(2)
b = tf.constant(3)

# 啓動默認的計算圖
with tf.Session() as sess:
    print("a=2, b=3")
    print("常量節點相加: %i" % sess.run(a+b))
    print("常量節點相乘: %i" % sess.run(a*b))

# 使用變量(variable)做爲計算圖的輸入
# 構造函數返回的值表明了Variable op的輸出 (session運行的時候,爲session提供輸入)
# tf Graph input
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)

# 定義一些操做
add = tf.add(a, b)
mul = tf.multiply(a, b)

# 啓動默認會話
with tf.Session() as sess:
    # 把運行每個操做,把變量輸入進去
    print("變量相加: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
    print("變量相乘: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))


# 矩陣相乘(Matrix Multiplication)
# 建立一個 Constant op ,產生 1x2 matrix.
# 該op會做爲一個節點被加入到默認的計算圖
# 構造器返回的值 表明了Constant op的輸出
matrix1 = tf.constant([[3., 3.]])
# 建立另外一個 Constant op 產生  2x1 矩陣.
matrix2 = tf.constant([[2.],[2.]])
# 建立一個 Matmul op 以 'matrix1''matrix2' 做爲輸入.
# 返回的值, 'product', 表達了矩陣相乘的結果
product = tf.matmul(matrix1, matrix2)
# 爲了運行 matmul op 咱們調用 session 的 'run()' 方法, 傳入 'product'
# ‘product’表達了 matmul op的輸出. 這代表咱們想要取回(fetch back)matmul op的輸出
# op 須要的全部輸入都會由session自動運行. 某些過程能夠自動並行執行
#
# 調用 'run(product)' 就會引發計算圖上三個節點的執行:2個 constants 和一個 matmul.
# ‘product’op 的輸出會返回到 'result':一個 numpy `ndarray` 對象.
with tf.Session() as sess:
    result = sess.run(product)
    print('矩陣相乘的結果:', result)
    # ==> [[ 12.]]

#保存計算圖
writer = tf.summary.FileWriter(logdir='logs', graph=tf.get_default_graph())
writer.flush()

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'node

這是log日誌級別設置git

import os  
os.environ["TF_CPP_MIN_LOG_LEVEL"]='1' # 這是默認的顯示等級,顯示全部信息  
os.environ["TF_CPP_MIN_LOG_LEVEL"]='2' # 只顯示 warning 和 Error   
os.environ["TF_CPP_MIN_LOG_LEVEL"]='3' # 只顯示 Error

a = tf.placeholder(tf.int16) github

b = tf.placeholder(tf.int16) api

這裏a,b是做變量處理。tf.placeholder()是佔位符,會要求指定變量類型(至關於預先定義),以後會把值傳入進去。網絡

print("變量相加: %i" % sess.run(add, feed_dict={a: 2, b: 3})) session

print("變量相乘: %i" % sess.run(mul, feed_dict={a: 2, b: 3})) app

如上面這段代碼所示,在tf.Session.run()中使用feed_dict來傳入tensor.feed_dict也能夠同時傳入多個tensor。ide

思考:tf.placehold()和tf.Variable()有什麼區別呢?函數

tf.Variable適合一些須要初始化或被訓練而變化的權重或參數,而tf.placeholder適合一般不會改變的被訓練的數據集。測試


Variable:主要是用於訓練變量之類的。好比咱們常常使用的網絡權重,偏置。
值得注意的是Variable在聲明是必須賦予初始值。在訓練過程當中該值極可能會進行不斷的加減操做變化。
名稱的真實含義,在於變量,也即在真實訓練時,其值是會改變的,天然事先須要指定初始值;
placeholder:也是用於存儲數據,可是主要用於feed_dict的配合,接收輸入數據用於訓練模型等。placeholder值在訓練過程當中會不斷地被賦予新的值,用於批訓練,基本上其值是不會輕易進行加減操做。

placeholder在命名時是不會須要賦予值得,其被賦予值得時間實在feed_dict時。其命名的緣由所在,僅僅做爲一種佔位符;

tf.placeholder(dtype, shape=None, name=None)

此函數能夠理解爲形參,用於定義過程,在執行的時候再賦具體的值

參數:
dtype:數據類型。經常使用的是tf.float32,tf.float64等數值類型
shape:數據形狀。默認是None,就是一維值,也能夠是多維,好比[2,3], [None, 3]表示列是3,行不定
name:名稱。

參考文獻:http://blog.csdn.net/hhtnan/article/details/78990618


product = tf.matmul(matrix1, matrix2)

爲了運行 matmul op 咱們調用 session 的 'run()' 方法, 傳入 'product' # ‘product’表達了 matmul op的輸出. 這代表咱們想要取回(fetch back)matmul op的輸出。op 須要的全部輸入都會由session自動運行. 某些過程能夠自動並行執行。調用 'run(product)' 就會引發計算圖上三個節點的執行:2個 constants 和一個 matmul。 ‘product’op 的輸出會返回到 'result':一個 numpy `ndarray` 對象.

 

 

保存計算圖

writer = tf.summary.FileWriter(logdir='logs', graph=tf.get_default_graph())

writer.flush()#強制寫入

將你的event存儲在logs_dir中,而後在terminal中輸入tensorboard --logdir=logs_dir 打開tensorboard

 

Tensorflow實現K近鄰分類器

import numpy as np
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 導入MNIST數據集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("mnist_data/", one_hot=True)

# 咱們對MNIST數據集作一個數量限制,
Xtrain, Ytrain = mnist.train.next_batch(5000) #5000 用於訓練(nn candidates)
Xtest, Ytest = mnist.test.next_batch(200) #200 用於測試
print('Xtrain.shape: ', Xtrain.shape, ', Xtest.shape: ',Xtest.shape)
print('Ytrain.shape: ', Ytrain.shape, ', Ytest.shape: ',Ytest.shape)

# 計算圖輸入佔位符
xtrain = tf.placeholder("float", [None, 784])
xtest = tf.placeholder("float", [784])

# 使用L1距離進行最近鄰計算
# 計算L1距離
distance = tf.reduce_sum(tf.abs(tf.add(xtrain, tf.negative(xtest))), axis=1)
# 預測: 得到最小距離的索引 (根據最近鄰的類標籤進行判斷)
pred = tf.arg_min(distance, 0)
#評估:判斷給定的一條測試樣本是否預測正確

# 初始化節點
init = tf.global_variables_initializer()

#最近鄰分類器的準確率
accuracy = 0.

# 啓動會話
with tf.Session() as sess:
    sess.run(init)
    Ntest = len(Xtest)  #測試樣本的數量
    # 在測試集上進行循環
    for i in range(Ntest):
        # 獲取當前測試樣本的最近鄰
        nn_index = sess.run(pred, feed_dict={xtrain: Xtrain, xtest: Xtest[i, :]})
        # 得到最近鄰預測標籤,而後與真實的類標籤比較
        pred_class_label = np.argmax(Ytrain[nn_index])
        true_class_label = np.argmax(Ytest[i])
        print("Test", i, "Predicted Class Label:", pred_class_label,
              "True Class Label:", true_class_label)
        # 計算準確率
        if pred_class_label == true_class_label:
            accuracy += 1
    print("Done!")
    accuracy /= Ntest
    print("Accuracy:", accuracy)

 

tf.reduce_sum()

官方給的api

reduce_sum(
    input_tensor,
    axis=None,
    keep_dims=False,
    name=None,
    reduction_indices=None
)

input_tensor:表示輸入
axis:表示在那個維度進行sum操做。當axis=0表示按列相加,當axis=1表示按行相加
keep_dims:表示是否保留原始數據的維度,False至關於執行完後原始數據就會少一個維度。
reduction_indices:爲了跟舊版本的兼容,如今已經不使用了。

 

tf.arg_min

官方api

tf.argmin
argmin(
    input,
    axis=None,
    name=None,
    dimension=None,
    output_type=tf.int64
)

Returns the index with the smallest value across axes of a tensor. (deprecated arguments)
返回在所給軸(axis)上最小值的索引
SOME ARGUMENTS ARE DEPRECATED. They will be removed in a future version. Instructions for updating: Use the axis argument instead Note that in case of ties the identity of the return value is not guaranteed.
有一些是過期的。他們將在將來的版本中刪除。說明:使用軸參數代替注意的返回值的身份是沒有保證的狀況下。

參考文獻:http://blog.csdn.net/NockinOnHeavensDoor/article/details/78853142

np.argmin

numpy.argmax(a, axis=None, out=None)[source]           Returns the indices of the maximum values along an axis.

Parameters:

       a : array_like

             Input array.

       axis : int, optional

          By default, the index is into the flattened array, otherwise along the specified axis.

       out : array, optional

        If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.

Returns:

       index_array : ndarray of ints

       Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

相關文章
相關標籤/搜索