2020 tensor 随想

作者: zidea | 来源:发表于2020-06-09 20:50 被阅读0次
    machine_learning.jpg
    import numpy as np
    

    tensor

    tensor 并不等同于 vector,在机器学习中 tensor 以及 tensor 的操作是基础,想要学习好机器学习前提是我们需要熟悉掌握 tensor 形状,tensor 运算以及 tensor 的形状变换。特变是在卷积神经网络中,我们不断变换 tensor 形状和运算来实现图像识别与目标检测。

    tensor_1 = np.array([1,2,3,4,5])
    tensor_1.ndim
    
    1
    

    tensor_1 是一个 1 维向量,数据有几个轴 tensor 就有

    arr = np.random.randint(30,size=(2,4))
    
    arr
    
    array([[ 3, 24, 20, 14],
           [17, 19, 29, 28]])
    

    我们都生活在 3 维空间,所以最熟悉可以想象到也就是限于 3 维矩阵,也就是 tensor。如果空间感稍微弱一些,二维空间大家应该不会陌生。其实数学中 我们用到最多也是 2 维 tensor 。但是深度学习中,我们常常甚至大多数情况都是和高维 tensor 打交道。这样就需要我们对高维 tensor

    tensor_1 = np.random.randint(10,size=(3,2))
    
    tensor_2 = np.array([1,2])
    print(np.dot(tensor_1,tensor_2))
    
    [14 25 19]
    

    广播

    应该翻译维广播还是扩展呢,这个我们需要深究。我们先看什么是广播以及广播的应用。我们知道两个 tensor 在做内积或者加分运算时,需要两个 tensor 形状。但是如果其中一个 tensor 在个维度并不完全例如

    x = np.random.randint(10,size=(2,3))
    x
    
    array([[5, 0, 2],
           [8, 4, 1]])
    
    y = np.random.randint(10,size=(3,))
    y
    
    array([9, 1, 0])
    
    res = x + y
    res
    
    array([[14,  1,  2],
           [17,  5,  1]])
    

    y 为了能够和 x 进行加法运算,先将自己维度扩展到 (2 \times 3) 然后在将 row 复制扩展 row 上后在进行加法运算

    tensor reshaping

    我们先说 tensor reshaping 的重要性,然后在说如何对 tensor 进行 reshape。因为这个 reshaping 操作是比较抽象的,所以需要通过训练才能让我们熟悉 tensor 的 reshaping。我们还是用大家最熟悉的 mnist 来解释 tensor reshaping 在深度学习中如何应用这件事。

    from keras.datasets import mnist
    
    (train_images,train_labels),(test_images,test_labels) = mnist.load_data()
    
    train_images.shape
    
    (60000, 28, 28)
    

    观察我们都会知道 60000 也就是第一维度表示图片数量,也就是样本数量,接下来是图片宽和高通过这样 2 维空间表示一张图片。但是最开始的全连接层是没有空间维度,所以我们就需要将 28 \times 28 二维 tensor 变为 1 维 tensor 输入到全连接层。我们定义 2 维(60000,x) x 大小我们还不知道可以使用 28 \times 38 表示 tensor 第 2 维的大小,也可以直接使用 -1 让计算机帮助我们计算第 2 维的大小。

    train_images = train_images.reshape((60000,-1))
    
    train_images.shape
    
    (60000, 784)
    

    tensor transpose

    x = np.zeros((2,3))
    x
    
    array([[0., 0., 0.],
           [0., 0., 0.]])
    
    y = np.transpose(x)
    y
    
    array([[0., 0.],
           [0., 0.],
           [0., 0.]])
    
    x = np.arange(24)
    y = x.reshape(2,3,4)
    y
    
    array([[[ 0,  1,  2,  3],
            [ 4,  5,  6,  7],
            [ 8,  9, 10, 11]],
    
           [[12, 13, 14, 15],
            [16, 17, 18, 19],
            [20, 21, 22, 23]]])
    
    z = np.transpose(y)
    z
    
    array([[[ 0, 12],
            [ 4, 16],
            [ 8, 20]],
    
           [[ 1, 13],
            [ 5, 17],
            [ 9, 21]],
    
           [[ 2, 14],
            [ 6, 18],
            [10, 22]],
    
           [[ 3, 15],
            [ 7, 19],
            [11, 23]]])
    
    z.shape
    
    (4, 3, 2)
    
    
    

    相关文章

      网友评论

        本文标题:2020 tensor 随想

        本文链接:https://www.haomeiwen.com/subject/bxnetktx.html