1势就、TensorFlow(tf)變量的類型及使用方法
(1) tf.constant() ? ? ? ?
????先定義變量泉瞻,后直接使用 tf.Session()
????????import tensorflow as tf
? ? ? ? # Define constant tensors
? ? ????a = tf.constant(2)
? ? ????b = tf.constant(3)
? ? ? ? with tf.Session() as sess:
? ? ? ? ????print( ?sess.run(a+b) ?) ? ? ? ?# 5
? ??
(2) tf.placeholder()
????先定義變量脉漏,再定義操作,最后使用 tf.Session() 及 feed_dict
????????import tensorflow as tf
? ? ? ? a = tf.placeholder(tf.int16)
? ? ? ? b = tf.placeholder(tf.int16)
? ? ? ? # Define some operations
? ??????add = tf.add(a, b)
? ? ? ? with tf.Session() as sess:
? ? ? ? ? ? print( ?sess.run(add, feed_dict={a:2, b:3}) ?) ? ? ? ?# 5
2袖牙、Eager API????????用 tfe 實(shí)現(xiàn) sess 的作用
(1)顯示 Tensor
? ? import tensorflow as tf
? ? import tensorflow.contrib.eager as tfe
? ? # Set Eager API
? ? tfe.enable_eager_execution()
? ? # Define constant tensors
? ??a = tf.constant(2)
? ? b?= tf.constant(3)
? ? print(a+b) ? ? ? ?# 5
? ? # Define matrix tensor
? ??a = tf.constant([[2., 1.],?[1., 0.]], dtype=tf.float32)
? ??b = np.array([[3., 0.],?[5., 1.]], dtype=np.float32)
? ??c = a + b
? ??d = tf.matmul(a, b)
????print("a + b =%s"%c) ? ? ? ?# [ [5., 1.], [6., 1.] ]
? ??print("a * b =%s" % d) ? ? ? ?# [ [11., 1], [3., 0.] ]
(2)用于訓(xùn)練
? ? 有點(diǎn)難以總結(jié)侧巨,可以參照代碼
3、batch_size 的作用
? ? 可以參考
? ? batch_size 盲目小鞭达,越難收斂
? ? batch_size 盲目大司忱,對(duì)參數(shù)的修正越緩慢
4、機(jī)器學(xué)習(xí)中常見的計(jì)算準(zhǔn)確率三步曲
? ? 假設(shè) y 為正確便簽畴蹭;pred 為預(yù)測(cè)標(biāo)簽坦仍。 一般均為 [ ?[1, 0, 0, ... 0] , ?[0, 0, 1, 0 ...., 0], ...[0, 1, 0, 0,...0] ] 形式。?
假設(shè) y = [ [1, 0, 0], ?[1, 0, 0], ?[0, 0, 1], ?[0, 1, 0] ?]; ? ? ? ?(即共有4個(gè)樣例叨襟,3種類型)
? ? ? ? pred?= [ [0.8, 0.1, 0.1], ?[0.2, 0.1, 0.7], ?[0.2, 0.3, 0.5], ?[0.1, 0.6, 0.3] ?]
(1)找標(biāo)簽對(duì)應(yīng)位置即為類別
? ? a = tf.argmax(y, 1) ? ? ? ?# [ 0, 0, 2, 1]
? ? b = tf.argmax(pred, 1) ? ? ? ?# [0, ?2, 2, 1]
(2)查看對(duì)應(yīng)是否相等
? ? c = tf.equal(a, b) ? ? ? ?# [ ?True, False, True, True]
(3)計(jì)算準(zhǔn)確率
? ? acc = tf.reduce_mean( tf.cast(c, tf.float32) ) ? ? ? ?# 0.75