1. 程式人生 > >TensorFlow 學習(七) — 常用函式 api、tf.nn、tf.keras

TensorFlow 學習(七) — 常用函式 api、tf.nn、tf.keras

0. 四則運算

  • 平方:tf.square(),開方:tf.sqrt()
  • tf.add()、tf.sub()、tf.mul()、tf.div()、tf.mod()、tf.abs()、tf.neg()

1. 簡單數理統計

RnR\mathbb R^n\rightarrow \mathbb R(從向量到標量),意味著一種約簡(reduce)。

  • 均值:tf.reduce_mean,求和:tf.reduce_sum

    • stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
    >> tf.InteractiveSession()
    >> x = tf.constant(np.ones(6).reshape(2, 3))
    >> x.eval()
    array([[1., 1., 1.],
           [1., 1., 1.]])
    
    >> tf.reduce_sum(x).eval()
    6.0
    >> tf.reduce_sum(x, 0).eval()
    array([2., 2., 2.])
    >> tf.reduce_sum(x, 1).eval()
    array([3., 3.])
    >>  tf.reduce_sum(x, 1, keepdims=True).eval()
    array([[3.],
           [3.]])
    
  • 最大最小(極值):tf.reduce_max/tf.reduce_min

2. 初始化子(initializer)

  • tf.zeros_initializer()
  • tf.ones_initializer()
  • tf.constant_initializer()
    • tf.constant_initializer(0.) ⇒ float
    • tf.constant_initializer(0, dtype=tf.int64)
  • tf.random_normal_initializer()

與 tf.global_variable_initializer() 所不同的是,以上這些返回的是物件(<tensorflow.python.ops.init_ops.Constant/RandomNormal/Ones/Zeros at 0xXXX>

),而 tf.global_variable_initializer() 返回的則是一種 tf.Operation(<tf.Operation 'init_N' type=NoOp>),

3. 矩陣向量運算

  • tf.diag、tf.transpose、tf.matmul、
  • tf.matrix_determinant(方陣行列式)、tf.matrix_inverse(方陣求逆)

4. tf.nn

  • activation

    • tf.nn.relu
    • tf.nn.softmax:多分類的輸出層
  • softmax + cross entropy:

    tf.nn.softmax_cross_entropy_with_logits(logits, labels) ⇒ tf.reduce_mean()
    

5. 優化、損失與評價

  • optimizer:
    • tf.train.AdamOptimizer()
  • loss:
    • ‘sparse_categorical_crossentropy’
  • metrics
    • ‘accuracy’

6. tf.keras

  • 以 mnist 的 60002828 的資料集為例:

    • 搭建模型的拓撲結構
    model = keras.Sequential([
    	keras.layers.Flatten(input_shape=(28, 28)),
    	keras.layers.Dense(128, activation=tf.nn.relu),
    	keras.layers.Dense(10, activation=tf.nn.softmax)
    ])
    

    keras.layers.Flatten(input_shape=(28, 28))將影象由二維拉伸為1維;

    • 模型編譯:
    model.compile(optimizer=tf.train.AdamOptimizer(),
    	loss='sparse_categorical_crossentropy',
    	metrics=['accuracy'])
    
    • 模型訓練(此時傳入資料)
    model.fit(X_train, y_train, epochs=5)
    
    • 模型評估:
    test_loss, test_accuracy = model.evaluate(X_test, y_test)
    

1. 基本

  • tf.clip_by_value() 截斷,常和對數函式結合使用

    # 計算交叉熵
    crose_ent = -tf.reduce_mean(tf.log(y_*tf.clip_by_value(y, 1e-10, 1.)))
    
    a = tf.reshape(tf.range(6, dtype=tf.float32), [2, 3])
    tf.clip_by_value(a, 2.5, 4.5)           # 將值限定在 2.5 和 4.5 之間
    array([[ 2.5,  2.5,  2.5],
           [ 3. ,  4. ,  4.5]], dtype=float32)
    

2. 條件分支:tf 下的三目運算子

f(x,y)={a(xy),x&gt;ya(yx),xy f(x,y)=\left\{ \begin{array}{l} a(x-y), &amp; x&gt;y\\ a(y-x),&amp;x\leq y \end{array} \right.

tf.select(tf.greater(v1, v2), a*(v1-v2), a*(v2-v1))

當然上式也可化為:f(x,y)=axyf(x,y)=a|x-y|

3. map_fn

  • tf.map_fn(fn, elems):接受一個函式物件,然後用該函式物件對集合(elems)中的每一個元素分別處理,

    def preprocessing_image(image, training):
    	image = ...
    	return image
    
    def preprocessing_images(images, training):
    	images = tf.map_fn(lambda image: preprocessing_image(image, training), images)
    	return images
    

相關推薦

no