tensorflow2.0学习笔记(一)

    技术2022-07-10  211

    一、维度变换

    import tensorflow as tf a = tf.random.normal((4,3,2,1)) a.shape TensorShape([4, 3, 2, 1])

    转置

    tf.transpose(a).shape TensorShape([1, 2, 3, 4])

    perm,设置转置维度,下面的例子是把第3和第4维度进行转置

    tf.transpose(a,perm=[0,1,3,2]).shape TensorShape([4, 3, 1, 2])

    添加维度

    a = tf.random.normal([4,35,8])

    添加第0维度

    tf.expand_dims(a,axis=0).shape TensorShape([1, 4, 35, 8])

    添加第3维度

    tf.expand_dims(a,axis=3).shape TensorShape([4, 35, 8, 1])

    减少维度,只能减少shape=1的维度

    tf.squeeze(tf.zeros([1,2,1,1,3])).shape TensorShape([2, 3]) a = tf.zeros([1,2,1,3]) tf.squeeze(a,axis=0).shape TensorShape([2, 1, 3])

    二、广播

    它根据维度自动对齐

    x = tf.random.normal([4,32,32,3]) (x + tf.random.normal([3])).shape TensorShape([4, 32, 32, 3]) (x + tf.random.normal([32,32,1])).shape TensorShape([4, 32, 32, 3]) (x + tf.random.normal([4,1,1,1])).shape TensorShape([4, 32, 32, 3])

    广播例子,broadcast和tile的比较

    a = tf.ones([3,4]) a.shape TensorShape([3, 4]) a1 = tf.broadcast_to(a,[2,3,4]) a1.shape TensorShape([2, 3, 4]) a2 = tf.expand_dims(a,axis=0) a2.shape TensorShape([1, 3, 4]) a3 = tf.tile(a2,[2,1,1]) a3.shape TensorShape([2, 3, 4])

    三、数学运算

    两个张量之间的加减乘除

    a = tf.ones([2,2]) b = tf.fill([2,2],2.) tf.math.log(a) <tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[0., 0.], [0., 0.]], dtype=float32)> tf.exp(a) <tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[2.7182817, 2.7182817], [2.7182817, 2.7182817]], dtype=float32)>

    但这里是$\log_e , 没 有 其 他 比 如 ,没有其他比如 \log_2 , , \log_8 , 根 据 对 数 换 底 公 式 , ,根据对数换底公式, \frac{log_a b}{log_a c}=log_c b$,我们可以得出任意的对数

    tf.math.log(8.)/tf.math.log(2.) <tf.Tensor: shape=(), dtype=float32, numpy=3.0>

    指数

    tf.pow(b,3) <tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[8., 8.], [8., 8.]], dtype=float32)> tf.pow(b,1/2) <tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[1.4142135, 1.4142135], [1.4142135, 1.4142135]], dtype=float32)>

    矩阵相乘(叉乘)

    tf.matmul(a,b) <tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[4., 4.], [4., 4.]], dtype=float32)>

    相乘和加的广播

    x = tf.ones([4,2]) w = tf.ones([2,1]) b = tf.constant(0.1) x @ w + b # @代表矩阵叉乘 <tf.Tensor: shape=(4, 1), dtype=float32, numpy= array([[2.1], [2.1], [2.1], [2.1]], dtype=float32)>
    Processed: 0.017, SQL: 9