0. 四则运算
- 平方:tf.square(),开方:tf.sqrt()
- tf.add()、tf.sub()、tf.mul()、tf.div()、tf.mod()、tf.abs()、tf.neg()
1. 简单数理统计
R n → R \mathbb R^n\rightarrow \mathbb R Rn→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 的数据集为例:
<a href=“https://www.tensorflow.org/tutorials/keras/basic_classification”, target="_blank">Train your first neural network: basic classification </>
- 搭建模型的拓扑结构
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 ( x − y ) , x > y a ( y − x ) , x ≤ y f(x,y)=\left\{ \begin{array}{l} a(x-y), & x>y\\ a(y-x),&x\leq y \end{array} \right. f(x,y)={a(x−y),a(y−x),x>yx≤y
tf.select(tf.greater(v1, v2), a*(v1-v2), a*(v2-v1))
当然上式也可化为: f ( x , y ) = a ∣ x − y ∣ f(x,y)=a|x-y| f(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