一個TensorFlow的運算可以看作是一個數據流圖。
一個圖呢則由一組操作和數據集組成。
- 操作(operation)代表運算單元
- 數據(tensor) 代表在各運算單元流動的數據單元
要想使用一個數據流圖,必須把它注冊為默認的圖。
注意:圖這個class並不是線程安全的,它所有的方法也不是。
將一個圖設為默認的圖的方法:
g = tf.Graph() with g.as_default(): # 將圖設為默認 # define operations and tensors in g c = tf.constant(30.0)
as_default(self)
返回一個將Graph設為默認的context manager。如果你想要在一個進程中創建多個圖考慮使用。如果你不顯示調用,一個全局默認圖將被提供。
默認圖所屬當前線程,如果你創建了一個新的線程,你必須在那個線程中顯示調用as_default方法。
創建常量tensor
constant(value, dtype=None, shape=None, name='Const', verify_shape=False)
'''
Args:
value: A constant value (or list) of output type `dtype`.
dtype: The type of the elements of the resulting tensor.
shape: Optional dimensions of resulting tensor.
name: Optional name for the tensor.
verify_shape: Boolean that enables verification of a shape of values.
Returns:
A Constant Tensor.
Raises:
TypeError: if shape is incorrectly specified or unsupported.
'''
傳入value創建常量tensor。value可以是一個常量值或常量列表。 參數shape是可選的,如果不提供默認為傳入value的shape。
同理,dtype也是可選的,不提供則默認為傳入value的dtype。
```python
# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]
# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
[-1. -1. -1.]]
```
創建變量tensor
w = tf.Variable(<initial-value>, name=<optional-name>)
一個變量維持圖的狀態。 變量在定義的時候要聲明它的類型和shape, 在創建之后雖然值是可以改變的, 但類型和shape是固定的。
和其他tensor一樣,被創建的變量可以被圖中的操作當作輸入使用。
當你啟用已經定義好的圖時,所有變量必須顯示的被初始化,之后你才可以運行操作使用他們的值。你也可以從文件中讀取完成初始化步驟。
創建placeholder
placeholder(dtype, shape=None, name=None)
給一個tensor插入placeholder,並且會在之后補充進去。
通過`Session.run()`的備選參數`feed_dict` 將之前的placeholder的值補進去, 如果你沒有喂進任何數據就運行會話對象將報錯。
```python x = tf.placeholder(tf.float32, shape=(1024, 1024)) y = tf.matmul(x, x) with tf.Session() as sess: print(sess.run(y)) # ERROR: will fail because x was not fed. rand_array = np.random.rand(1024, 1024) print(sess.run(y, feed_dict={x: rand_array})) # Will succeed. ```
計算logits tensor
logits = tf.matmul(tf_train_dataset, weights) + biases
計算softmax cross entropy,loss tensor
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))
softmax_cross_entropy_with_logits_v2(_sentinel=None, labels=None, logits=None, dim=-1, name=None)
Args:
_sentinel: Used to prevent positional parameters. Internal, do not use.
labels: Each row `labels[i]` must be a valid probability distribution.
logits: Unscaled log probabilities.
dim: The class dimension. Defaulted to -1 which is the last dimension.
name: A name for the operation (optional).
Returns:
A 1-D `Tensor` of length `batch_size` of the same type as `logits` with the
softmax cross entropy loss.
計算probability errors。 對於每一個想要預測的內容, 它必須有且只有一個標簽。
參數為logits和labels,這個函數內部會自動處理soft max。
softmax: 將score轉化成probability
def softmax(x): """Compute softmax values for each sets of scores in x.""" return np.exp(x) / np.sum(np.exp(x), axis = 0)
one-hot-encoding: 正確的label標為1,其他均為0. 比如有a,b,c三個label,a為正確的label標為1,b和c標為0
cross-entropy(用來衡量performance):
計算所有樣本的綜合loss:
優化處理Optimizer: Gradient Descent Optimizer, 定義operation
使用梯度下降法找到最小的loss。 這個operation會更新涉及到的tensor的值。
class GradientDescentOptimizer(tensorflow.python.training.optimizer.Optimizer)
__init__(self, learning_rate, use_locking=False, name='GradientDescent') Construct a new gradient descent optimizer. Args: learning_rate: A Tensor or a floating point value. The learning rate to use.
minimize(self, loss, global_step=None, var_list=None, gate_gradients=1, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None) Add operations to minimize `loss` by updating `var_list`. This method simply combines calls `compute_gradients()` and `apply_gradients()`.
If you want to process the gradient before applying them call `compute_gradients()` and `apply_gradients()` explicitly instead of using this function. Args: loss: A `Tensor` containing the value to minimize. global_step: Optional `Variable` to increment by one after the variables have been updated. Returns: An Operation that updates the variables in `var_list`. If `global_step` was not `None`, that operation also increments `global_step`. Raises: ValueError: If some of the variables are not `Variable` objects.
什么是梯度下降?
誤差方程 (Cost Function). 用來計算預測出來的和我們實際中的值有多大差別. 在預測數值的問題中. W是我們神經網絡中的參數, 假設我們初始化的 W 在一個位置. 而這個位置的斜率也就是梯度下降中的梯度. loss誤差最小的時候正是這條曲線最低的地方, 不過 W 卻不知道這件事情, 他目前所知道的就是梯度線為自己在這個位置指出的一個下降方向, 我們就要朝着這個梯度的方向下降一點點. 在做一條切線, 發現我還能下降, 那我就朝着梯度的方向繼續下降, 這時, 再展示出現在的梯度, 因為梯度線已經躺平了, 我們已經指不出哪邊是下降的方向了, 所以這時我們就找到了 W 參數的最理想值. 簡而言之, 就是找到梯度線躺平的點.
Session(會話)
用來運行tensorflow operation的類
會話對象封裝了一個供ops類執行並且可以評估tensor的環境。
會話類會擁有自己的資源,為確保在使用后這些資源被釋放,可以使用context manager
# Using the context manager. with tf.Session() as sess: sess.run(...)
在初始化創建一個會話對象的時候,如果沒有指明圖那么一個默認的圖會被啟用。如果你擁有多個圖,那么你需要為每一個圖初始化一個會話對象。
在會話類中,首先要初始化所有變量。使用global_variables_initializer()返回一個op並運行來初始化。
global_variables_initializer()
Returns an Op that initializes global variables.
Returns:
An Op that initializes global variables in the graph.